使用IO进行文件的复制操作

时间:2022-08-21 21:37:14
1.字符流通过缓存区进行文件的复制操作:

public class TestPerson {
public static void main(String[] args) {
 BufferedReader br=null;
 BufferedWriter bw=null;
 try {
  br=new BufferedReader(new FileReader("d://jf.txt"));
  bw=new BufferedWriter(new FileWriter("e://fu.txt"));
  String line=null;
  while((line=br.readLine())!=null){
   bw.write(line);
   bw.flush();
   
  }
 } catch (FileNotFoundException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
 finally{
  if(br!=null){
   try {
    br.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  if(bw!=null){
   try {
    bw.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
 
}
}

2.字节流的复制操作:

public static void main(String[] args) {
 FileInputStream fis=null;
 FileOutputStream fos=null;
 try {
  fis=new FileInputStream(new File("d://jf.txt"));
  fos=new FileOutputStream(new File("e://fu.txt"));
  byte bt[]=new byte[1024];
  int len=-1;
  while((len=fis.read(bt))!=-1){
   fos.write(bt,0,len);
   fos.flush();
  }
 } catch (FileNotFoundException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
 finally{
  if(fis!=null){
   try {
    fis.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  if(fos!=null){
   try {
    fos.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
 
}

}