有一个我们从中读取的文本文件,然后我们希望在对其他文本文件进行一些小的更改后将其写入,但是问题是,如果使用以下命令,为什么会有不同的结果
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
最佳答案
使用基于流的API,您不可能在同一循环中读取和写入文件。您将必须创建一个新文件并复制所有相同内容,并添加新内容。您现在正在做的事情具有不可预测的行为。如果仍然想同时读写,则必须使用RandomAccessFile
,但这要复杂得多。
关于java - 发生字符串标记错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10411271/