文件拷贝

2018-07-06  本文已影响0人  MrL槑槑
public class CopyFileTest extends BaseTest {

    @Test
    public void testCopyFile(){
        // 字节拷贝 FileInputStream、FileOutputStream
        InputStream in = null;
        OutputStream outputStream = null;
        try {
            // 传入文件路径
            File file = new File("/Users/a499827593/Desktop/a.txt");
            File out = new File("/Users/a499827593/Desktop/b.txt");
            outputStream = new FileOutputStream(out);
            in = new FileInputStream(file);
            int read;
            byte[] bytes = new byte[1024];
            while((read=in.read(bytes)) != -1){
                outputStream.write(bytes,0,bytes.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.flush();
                outputStream.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void testCopyFileChannel(){
        // 零拷贝 FileChannel
        FileChannel in = null;
        FileChannel out = null;
        try {
            File file = new File("/Users/a499827593/Desktop/c.txt");
            file.createNewFile();
            in = new FileInputStream(new File("/Users/a499827593/Desktop/a.txt")).getChannel();
            out = new FileOutputStream(file).getChannel();
            out.transferFrom(in,0,in.size());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void testCopyFileUtils(){
        // 使用 Commons IO 拷贝 --> FileUtils.copyFile(File srcFile, File destFile)
        try {
            File in = new File("/Users/a499827593/Desktop/a.txt");
            File out = new File("/Users/a499827593/Desktop/d.txt");
            FileUtils.copyFile(in,out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testCopyFiles(){
        // 使用 Files 拷贝 --> Files.copy(Path source, Path target)
        try {
            File in = new File("/Users/a499827593/Desktop/a.txt");
            File out = new File("/Users/a499827593/Desktop/d.txt");
            Files.copy(in.toPath(),out.toPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读