java_copy

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class FileDemo001 {
 public static void main(String args[]) throws IOException
 {
  String s1 = "D:\C4D Study Log\1.jpg";   //用字节流就可以复制任意文件,字符流就不能
  String s2 = "D:\BaiduNetdiskDownload";
  copy(s1,s2); //调用copy方法
 }
 private  static void copy(String src,String target) throws IOException
 {
  File srcFile = new File(src);  //源文件路径
  File tFile = new File(target);  //目标文件路径
  InputStream in = null;   
  OutputStream out = null;  //用于finally里做判断是否关闭流
  try {
   in = new FileInputStream(srcFile);  //字节流
   out = new FileOutputStream(tFile);
   byte[] bytes = new byte[1024];
   int len =-1;
   while((len=in.read(bytes))!=-1)//若len不为-1,就一直读写
   {
    out.write(bytes,0,len);  //用这个方法,确保不多读。
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }
  finally
  {
   if(in!=null) in.close();  //关闭流
   if(out!=null) out.close();
   
  }
  System.out.println("I got it!");   //看是否能执行完
  
  
 }
}
原文地址:https://www.cnblogs.com/wbwhy/p/12347193.html