Java一个字符串一个字符串地读取txt文件,然后编写另一个txt文件来保持单词的位置

Java一个字符串一个字符串地读取txt文件,然后编写另一个txt文件来保持单词的位置,java,file,file-read,file-writing,Java,File,File Read,File Writing,我有一个包含一些单词的txt文件,我想做的是一次读一个单词(字符串),操纵这个字符串,然后写另一个txt文件,但保留原始单词的位置。例如,如果我的输入如下: Hello, this is a test 我希望我的输出是两行的,就像输入一样。在我的代码中,我得到了如下结果(如追加): 这是我的这部分代码: Scanner sc2=null; try{ sc2 = new Scanner (new File(fileInput)); }catch(FileNotFoundExcep

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

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,则输入/输出将如下所示: 输入:

输出:

6, 8, 9,
5, 3

而不是像追加一样,每个单词都在一行中。

在阅读时写下这些行:

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);
    }
}

非常感谢!这解决了所有问题!现在我觉得有点愚蠢,看着答案…无论如何,再次感谢,它真的帮助了我。不愧于问。很高兴它帮助了我!
6, 8, 9,
5, 3
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);
    }
}