颠倒txt文件的行序
我需要导入一个文本文件并导出一个各行顺序相反的文本文件
示例输入:
abc
123
First line
预期输出:
First line
123
abc
这就是我到目前为止所拥有的。它颠倒了行的顺序,但不是行的顺序。 如有任何帮助,将不胜感激
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class reversetext {
public static void main(String[] args) throws IOException {
try {
File sourceFile = new File("in.txt");//input File Path
File outFile = new File("out.txt");//out put file path
Scanner content = new Scanner(sourceFile);
PrintWriter pwriter = new PrintWriter(outFile);
while(content.hasNextLine()) {
String s = content.nextLine();
StringBuffer buffer = new StringBuffer(s);
buffer = buffer.reverse();
String rs = buffer.toString();
pwriter.println(rs);
}
content.close();
pwriter.close();
}
catch(Exception e) {
System.out.println("Something went wrong");
}
}
}
解决方案
我能得出的最简单的答案是,使用JAVA 7+,而不是依赖像Stack
这样的过时构建块:
private static final String INPUT_FILE = "input.txt";
private static final String OUTPUT_FILE = "output.txt";
private static final String USER_HOME = System.getProperty("user.home");
public static void main(String... args) {
try {
try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(Paths.get(USER_HOME + "/" + OUTPUT_FILE)))) {
Files
.lines(Paths.get(USER_HOME + "/" + INPUT_FILE))
.collect(Collectors.toCollection(LinkedList::new))
.descendingIterator()
.forEachRemaining(writer::println);
}
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
只需读入输入文件并获取String
(Files#lines
)中的内容流。然后使用降序迭代器将它们收集到LinkedList
中,循环遍历它们并将它们写出到输出文件中。
相关文章