【问题标题】:Java read txt file string by string and write another txt keeping the position of the wordsJava逐个字符串读取txt文件并写入另一个保持单词位置的txt
【发布时间】:2015-06-08 13:20:50
【问题描述】:

我有一个包含一些单词的 txt 文件,我想做的是一次读取这个文件一个单词(字符串),操作这个字符串,然后写另一个 txt 文件,但保留原始单词的位置。例如,如果我的输入是这样的:

Hello, this is a
test

我希望我的输出在 2 行中,就像输入一样。使用我的代码,我得到了这样的东西(如附加):

hello,
this
is
a
test

这是我这部分的代码:

Scanner sc2=null;
try{
    sc2 = new Scanner (new File(fileInput));
    }catch(FileNotFoundException fnfe)
    {
    System.out.println("File not found");
    }
while(sc2.hasNextLine())
{
     Scanner s2=new Scanner (sc2.nextLine());
     while(s2.hasNext())
     {
      String word = s2.next();
     //Here i manipulate the string, and the result is stored in the string "a"

      try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileOutput, true))))
                {
                    out.println(a);
                }catch (IOException e){}
      }
}

(fileInput 和 fileOutput 的定义类似

String fileInput="path";

我认为我正在使用的 PrintWriter 只是对文件进行附加,但我试图用 FileWriter 和 OutputStreamWriter 替换这个 PrintWriter 但他们只写了最后一个字符串(他们用最新的字符串覆盖每个字符串,所以最后我得到了一个只有最后一个字符串的txt)。

我必须一次读取输入文件一个单词,因为我需要对其执行一些操作,然后我必须以与输入相同的方式写入输出。如果单词是数字并且我对它们的操作是简单的 +1,则输入/输出将如下所示: 输入:

5, 7, 8,
4, 2

输出:

6, 8, 9,
5, 3

而不是像新行中的每个单词一样追加。

【问题讨论】:

    标签: java file file-read file-writing


    【解决方案1】:

    边读边写:

    try(PrintWriter out = new PrintWriter(new BufferedWriter(
                                          new FileWriter(fileOutput)))) {
        while(sc2.hasNextLine()) {
            String line = sc2.nextLine();
            Scanner s2 = new Scanner(line);
            while(s2.hasNext()) {
                // use the words in line
            }
            // write the line
            out.println(line);
        }
    }
    

    【讨论】:

    • 非常感谢!这只是解决了一切!现在我觉得有点愚蠢,看着答案......无论如何再次感谢,它真的帮助了我。
    • 没有羞耻感。很高兴它有帮助!
    猜你喜欢
    • 2022-01-03
    • 2021-02-06
    • 2016-06-18
    • 2011-09-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    相关资源
    最近更新 更多