简体   繁体   English

逐行写入文件

[英]Write to file line by line

So my input file has some sentences, and i want to reverse the words in each sentence and keep the same order of sentences. 所以我的输入文件有一些句子,我想反转每个句子中的单词并保持句子的顺序相同。 I then need to print to a file. 然后,我需要打印到文件。 my problem is that my output file is only printing my last sentence, reversed. 我的问题是我的输出文件仅打印我的最后一句话,相反。

import java.util.*;
import java.io.*; 


 public class Reverser {   //constructor   Scanner sc = null ;   public
 Reverser(File file)throws FileNotFoundException, IOException {
     sc = new Scanner (file);   }

      public void reverseLines(File outpr)throws FileNotFoundException, IOExeption{

     //PrintWriter pw = new PrintWriter(outpr);
     while(sc.hasNextLine()){
       String sentence = sc.nextLine();
       String[] words = sentence.split(" ");
       ArrayList<String> wordsarraylist = new ArrayList<String>(Arrays.asList(words));
       Collections.reverse(wordsarraylist);



      FileWriter fw = new FileWriter(outpr); 
      BufferedWriter bw = new BufferedWriter(fw);

      for(String str: wordsarraylist) {
         bw.write(str + " ");


        bw.newLine();
        bw.close();
      }

     }   }
       }

That's because each time you loop, you reopen the file in overwrite mode. 这是因为每次循环时,都以覆盖模式重新打开文件。

Open the file before you start looping instead. 在开始循环之前,请先打开文件。

Don't use the append option here, it'll just make you open/close the file needlessly. 不要在这里使用append选项,它只会使您不必要地打开/关闭文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM