- import java.io.BufferedInputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.nio.ByteBuffer;
- import java.nio.channels.FileChannel;
- public class FileCopy{
- String fromFile="c:/a.txt";
- String toFile="d:/b.txt";
- public static void main(String[] args) {
- FileCopy fileCopy = new FileCopy();
- // fileCopy.nioFileCopy();
- fileCopy.streamFileCopyWithBuffer();
- // fileCopy.streamFileCopy();
- }
- public void streamFileCopyWithBuffer(){
- try {
- File fileIn = new File(fromFile);
- File fileOut = new File(toFile);
- FileInputStream fin = new FileInputStream(fileIn);
- BufferedInputStream bin = new BufferedInputStream(fin);
- FileOutputStream fout = new FileOutputStream(fileOut);
- byte[] buffer = new byte[8192];
- while (bin.read(buffer) != -1) {
- fout.write(buffer);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public void streamFileCopy(){
- try {
- File fileIn = new File(fromFile);
- File fileOut = new File(toFile);
- FileInputStream fin = new FileInputStream(fileIn);
- FileOutputStream fout = new FileOutputStream(fileOut);
- byte[] buffer = new byte[8192];
- while (fin.read(buffer) != -1) {
- fout.write(buffer);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public void nioFileCopy() {
- try {
- File fileIn = new File(fromFile);
- File fileOut = new File(toFile);
- FileInputStream fin = new FileInputStream(fileIn);
- FileOutputStream fout = new FileOutputStream(fileOut);
- FileChannel fcIn = fin.getChannel();
- ByteBuffer bf = ByteBuffer.allocate(8192);
- FileChannel fcOut = fout.getChannel();
- while (fcIn.read(bf) != -1) {
- bf.flip();
- fcOut.write(bf);
- bf.clear();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
转载于:https://blog.51cto.com/steveskylook/756545