BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String file_1 = console.readLine();
String file_2 = console.readLine();
console.close();
BufferedWriter fw = new BufferedWriter(new FileWriter(file_1));
BufferedReader fr_1 = new BufferedReader(new FileReader(file_1));
BufferedReader fr_2 = new BufferedReader(new FileReader(file_2));
String str;
while ((str = fr_2.readLine()) != null)
fw.write(str);
while ((str = fr_1.readLine()) != null)
fw.write(str);
fw.close();
fr_1.close();
fr_2.close();
My code is above and it solve the problem on the website.
However, when I test it in intellj with two of my txt files, the result is strange. Only the file_2 add into file_1, and the original file_1 cannot write into the file_1. Can anyone please help me?
Anyway, I tried FileWriter(file_1, true), and the file_1's context was writed into the file, however, the first line still remain the origin context. I know why there is still original context. What I really don't know is why I use FileWriter without append para, all things become strange?
Question about this code run in Intellj
正在讨论
评论 (2)
- 受欢迎
- 新
- 旧
你必须先登录才能发表评论
wangwangwang
9 四月 2021, 09:24
I have the same problem with you, but I use FileInputStream and FileOutputStream.I find that if you "new" a FileOutputStream before you close the FileInputStream, the two streams are on the same file, then will cause problem.Then I change the order of them, I try this code in my computer and it's OK, but I still don't know why. Here's my code:
0
syan
7 八月 2020, 12:24
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String fileName1 = br.readLine();
String fileName2 = br.readLine();
br.close();
FileInputStream in = new FileInputStream(fileName1);
FileOutputStream out = new FileOutputStream(fileName1);
FileInputStream in1 = new FileInputStream(fileName2);
byte[] bt = new byte[in.available()];
byte[] bt1 = new byte[in1.available()];
int data;
while(in.available() > 0){
data = in.read(bt);
}
in.close();
while (in1.available()>0){
data = in1.read(bt1);
out.write(bt1);
out.write(bt);
}
in1.close();
out.close();
}
0