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文件的行序
基础教程推荐
猜你喜欢
- 在springboot中如何给mybatis加拦截器 2023-04-29
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- JPA惰性列表上的流 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
