【发布时间】: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