package com.file.copy; import java.io.*; public class FileCopy { /** * 将一个源文件拷贝到一个目标目录中 * @param src * @param targetDir */ public static void copyFile(File src, File targetDir) throws IOException { InputStream is =null; OutputStream os =null; try{ //获取源文件输入流 is = new FileInputStream(src); //获取目标文件的输出流 (目标文件:目录+源文件名称) os = new FileOutputStream(new File(targetDir,src.getName())); //声明一个字节缓冲区 缓冲区越大,拷贝的效率越高,但是带来的空间损耗也越大 byte [] b = new byte[1024*1024]; //临时的变量表示实际读取的字节数 int len =0; System.out.println("开始拷贝"); while ((len=is.read(b))!=-1){ //写出读取的内容到输出流 os.write(b,0,len); } System.out.println("拷贝完成"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { if (os!=null){ os.close(); } if (is!=null){ is.close(); } } } public static void main(String[] args) throws IOException { //源文件 File src = new File("C:\\Users\\RD\\Desktop\\demo.txt"); //目标目录 File targetDir = new File("C:\\Users\\RD\\Desktop\\test.txt"); //文件拷贝 copyFile(src,targetDir); } }
关于Io流里面文件拷贝
最新推荐文章于 2024-05-01 23:01:20 发布