java复制文件的4种方式

第一种方法:使用FileInputStream以及FileOutputStream读写文件(有方法注释,建议放到工具中查看)


	public void fileCopy() {
		FileInputStream input = null;
		FileOutputStream output = null;

		try {

			input = new FileInputStream(new File("文件路径"));
			output = new FileOutputStream(new File("目标文件路径"));

			byte[] bt = new byte[1024];
			int realbyte = 0;
			/**      input.read(bt)
		     * Reads up to b.length bytes of data from this input
		     * stream into an array of bytes. This method blocks until some input
		     * is available.
		     *
		     * @param      b   the buffer into which the data is read.
		     * @return     the total number of bytes read into the buffer, or
		     *             -1 if there is no more data because the end of
		     *             the file has been reached.
		     * @exception  IOException  if an I/O error occurs.
		     */
			while ((realbyte = input.read(bt)) > 0) {
				
				/**   output.write(bt,0,realbyte)
			     * Writes len bytes from the specified byte array
			     * starting at offset off to this file output stream.
			     *
			     * @param      b     the data.
			     * @param      off   the start offset in the data.
			     * @param      len   the number of bytes to write.
			     * @exception  IOException  if an I/O error occurs.
			     */
				output.write(bt,0,realbyte);
			}
			
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (input != null) {
					input.close();
				}
				if (output != null) {
					output.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

第二种方法:效率比上一个高一些

public void fileCopy_channel() {
		FileChannel input = null;
		FileChannel output = null;

		try {
			input = new FileInputStream("givenfile").getChannel();
			output = new FileOutputStream("tofile").getChannel();
			/**
			 * Transfers bytes into this channel's file from the given readable byte channel.
			 *  @param  src
		     *         The source channel
		     *
		     * @param  position
		     *         The position within the file at which the transfer is to begin;
		     *         must be non-negative
		     *
		     * @param  count
		     *         The maximum number of bytes to be transferred; must be
		     *         non-negative
			 */
			output.transferFrom(input, 0, input.size());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (input != null) {
					input.close();
				}
				if (output != null) {
					output.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

第三种和第四种都是封装好的方法:

Apache Commons IO的方法FileUtils.copyFile(source, dest);

JDk以后才会有的Files.copy(source.toPath(), dest.toPath());

你可能感兴趣的:(JAVA)