在D盘创建文件test.txt,文件内容为“hello Java”,然后利用流把该文件拷贝到E盘目录下。

yinhr 2019-06-06 05:58:16
import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class test{ public static void main(String[] args) throws IOException{ File f = new File("d:\\test.txt"); File f1 = new File("e:\\test.txt"); FileReader reader = new FileReader(f); FileWriter writer = new FileWriter(f1); char[] buff = new char[512]; int len =0; while((len=reader.read(buff))!=-1){ String str = new String(buff,0,len); writer.write(str); writer.flush(); } reader.close(); writer.close(); } }
...全文
1335 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
这么写不是复制空文件吗 hello java呢
netwar 2019-06-07
  • 打赏
  • 举报
回复

public static void main(String[] args) throws Exception {
String path = "/Users/Desktop/aa";
File file1 = new File(path, "1.pdf");
File file2 = new File(path, "2.pdf");
if (!file1.exists()) {
System.out.println("文件" + file1 + "不存在");
return;
}
if (file2.exists()) {
System.out.println("文件已存在,执行删除操作");
file2.delete();
}
System.out.println("开始复制" + file2);
try (InputStream in = new BufferedInputStream(new FileInputStream(file1));
OutputStream out = new BufferedOutputStream(new FileOutputStream(file2))) {
int c = 0;
int total = 0;
while (c != -1) {
c = in.read();
total += c;
out.write((char) c);

}
System.out.println("文件复制完毕共" + total + "字节");
}
}
huhk 2019-06-06
  • 打赏
  • 举报
回复
还是用finally 关闭stream 吧,稳健些
牛肉滚蛋花 2019-06-06
  • 打赏
  • 举报
回复
引用 2 楼 夜雨奏长歌° 的回复:
[quote=引用 1 楼 牛肉滚蛋花的回复:]分不要就给我吧
我在aap上不会发博客,枯了[/quote]
yinhr 2019-06-06
  • 打赏
  • 举报
回复
引用 1 楼 牛肉滚蛋花的回复:
分不要就给我吧
我在aap上不会发博客,枯了
牛肉滚蛋花 2019-06-06
  • 打赏
  • 举报
回复
分不要就给我吧

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧