我们从中读取了一个文本文件,然后我们想在对其他文本文件稍作修改之后编写它,但问题是如果我们使用它会有不同的结果
System.out.println
以及我们何时使用pwPaperAuthor.println
?
代码如下:
package cn.com.author;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
//input:"IndexAuthors1997-2010.txt"
//output:"PaperAuthor1997-2010.txt"
public class PaperAuthors {
public static void main(String[] args) {
BufferedReader brIndexAuthors = null;
BufferedWriter bw = null;
PrintWriter pwPaperAuthor = null;
try {
brIndexAuthors = new BufferedReader(new InputStreamReader(
new FileInputStream("IndexAuthors1997-2010.txt")));
bw = new BufferedWriter(new FileWriter(new File(
"PaperAuthor1997-2010.txt")));
pwPaperAuthor = new PrintWriter(new OutputStreamWriter(
new FileOutputStream("PaperAuthor1997-2010.txt")));
/*
* line = brIndexAuthors.readLine();
*
* element=line.split("@"); String author=null; StringTokenizer st =
* new StringTokenizer(element[1],","); while(st.hasMoreTokens()) {
* author = st.nextToken(); pwPaperAuthor.println(element[0] + "+" +
* author); //~i++; }
*/
String line = null;
String element[] = new String[3];
String author = null;
int i = 0;
while ((line = brIndexAuthors.readLine()) != null) {
element = line.split("#@");
StringTokenizer st = new StringTokenizer(element[1], ",");
int num=st.countTokens();
while (st.hasMoreTokens()) {
author = st.nextToken();
pwPaperAuthor.println(element[0]+"@"+author+"@"+element[2]);
bw.write(element[0] + "@" + author + "@" + element[2]);
bw.newLine();
System.out.println(element[0]+"@"+author+"@"+element[2]);
i++;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}
如果
System.out.println(element[0]+"@"+author+"@"+element[2]);------>620850@Henk Ern
如果
pwPaperAuthor.println(element[0]+"@"+author+"@"+element[2]);
----->620850@Henk Ernstblock@2001
答案 0 :(得分:0)
使用基于流的API,您无法在同一循环中读取文件并写入文件。您必须创建一个新文件并复制相同的所有内容,并添加新内容。你现在在做什么有不可预测的行为。如果您仍想同时阅读和书写,则必须使用RandomAccessFile
,但这要复杂得多。