1

有一个我们从中读取的文本文件,然后我们想在对其他文本文件进行一些小的更改后将其写入,但问题是为什么我们使用 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
4

1 回答 1

0

使用基于流的 API,您无法在同一个循环中读取和写入文件。您将必须创建一个新文件并复制所有相同的内容,添加新内容。您现在正在做的事情具有不可预测的行为。如果您仍想同时读写,则必须使用RandomAccessFile,但这要复杂得多。

于 2012-05-02T09:58:47.197 回答