Java复制文件
如何将一个文件复制到另一个文件?
解决方法
这个例子显示了如何使用BufferedWriter类的read & write 方法将一个文件的内容复制到另一个文件。
import java.io.*; public class Main { public static void main(String[] args) throws Exception { BufferedWriter out1 = new BufferedWriter (new FileWriter("srcfile")); out1.write("string to be copied "); out1.close(); InputStream in = new FileInputStream (new File("srcfile")); OutputStream out = new FileOutputStream (new File("destnfile")); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); BufferedReader in1 = new BufferedReader (new FileReader("destnfile")); String str; while ((str = in1.readLine()) != null) { System.out.println(str); } in.close(); } }
结果
上面的代码示例将产生以下结果。
string to be copied