java 文件复制程序,Java如何复制文件?

在java编程中,如何将一个文件复制到另一个文件?

此示例显示如何使用BufferedWriter类的read()和write()方法将一个文件的内容复制到另一个文件中。

package com.yiibai; import java.io.*; public class CopyFile { public static void main(String[] args) throws Exception { String srcfile = "srcfile.txt"; String destnfile = "destnfile.txt"; BufferedWriter out1 = new BufferedWriter(new FileWriter(srcfile)); out1.write("Line 1 : string to be copiedn"); out1.write("Line 2 : to be copiedn"); 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(); } }

执行上述示例代码,将产生以下结果 –

Line 1 : string to be copied Line 2 : to be copied

示例-2

以下是将一个文件复制到另一个文件的另一个示例。

package com.yiibai; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class CopyFile2 { public static void main(String[] args) { FileInputStream ins = null; FileOutputStream outs = null; try { File infile = new File("F:/worksp/javaexamples/java_files/infile.txt"); File outfile = new File("F:/worksp/javaexamples/java_files/outfile.txt"); ins = new FileInputStream(infile); outs = new FileOutputStream(outfile); byte[] buffer = new byte[1024]; int length; while ((length = ins.read(buffer)) > 0) { outs.write(buffer, 0, length); } ins.close(); outs.close(); System.out.println("File copied successfully!!"); } catch (IOException ioe) { ioe.printStackTrace(); } } }

首先,创建一个文件:infile.txt,此文件中的内容就是上面CopyFile2.java文件的代码内容。

执行上述示例代码,将产生以下结果 –

File copied successfully!!

在执行完成上面示例程序后,打开文件:outfile.txt可以看到其中的内容与infile.txt文件的内容一样,说明复制文件内容成功。

¥ 我要打赏 纠错/补充 收藏

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值