Java中在磁盘上复制文件

  • 使用字节流实现
            public static void main(String[] args) throws IOException {
    		InputStream in = new FileInputStream(new File("F:\\test.py"));
    		byte[] bts = new byte[1024];
    		OutputStream out = new FileOutputStream(new File("D:\\test\\test.py"));
    		int len = 0;
    		while((len = in.read(bts))!=-1) {
    			out.write(bts, 0, len);
    		}
    		
    		out.close();
    		in.close();
    	}
    

      

  • 使用字符流实现
    • char数组作为缓存
              public static void main(String[] args) throws IOException {
      		FileReader r = new FileReader("F:\\test.py");
      		FileWriter w = new FileWriter("D:\\test\\test2.py");
      		char[] buf = new char[1024];
      		int c ;
      		while((c=r.read(buf))!=-1) {
      			w.write(buf,0,c);
      		}
      		r.close();
      		w.close();
      	}
      

        

    • 不使用数组做缓存,直接复制
              public static void main(String[] args) throws IOException {
      		FileReader r = new FileReader("F:\\test.py");
      		FileWriter w = new FileWriter("D:\\test\\test2.py");
      //		char[] buf = new char[1024];
      		int c ;
      		while((c=r.read())!=-1) {
      			w.write(c);
      		}
      		r.close();
      		w.close();
      	}    
      

        

posted @ 2018-03-09 16:00  *青锋*  阅读(220)  评论(0编辑  收藏  举报