美文网首页
文件拷贝

文件拷贝

作者: MrL槑槑 | 来源:发表于2018-07-06 13:19 被阅读0次
    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();
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:文件拷贝

          本文链接:https://www.haomeiwen.com/subject/rdwvuftx.html