【问题标题】:Write to file line by line逐行写入文件
【发布时间】:2015-09-23 06:32:17
【问题描述】:

所以我的输入文件有一些句子,我想反转每个句子中的单词并保持相同的句子顺序。然后我需要打印到文件。我的问题是我的输出文件只打印了我的最后一句话,颠倒了。

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

     }   }
       }

【问题讨论】:

  • 这行得通,但现在句子之间没有间隔,我不知道在循环中写“/n”的位置。

标签: java file reverse writetofile


【解决方案1】:

这是因为每次循环时,都会以覆盖模式重新打开文件。

在开始循环之前打开文件。

这里不要使用 append 选项,它只会让你不必要地打开/关闭文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-11
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多