Reverse the line order of a txt file(颠倒txt文件的行序)
本文介绍了颠倒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中,循环遍历它们并将它们写出到输出文件中。
这篇关于颠倒txt文件的行序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:颠倒txt文件的行序
基础教程推荐
猜你喜欢
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- Struts2 URL 无法访问 2022-01-01
