【问题标题】:Reverse the line order of a txt file反转txt文件的行序
【发布时间】:2021-12-30 22:14:56
【问题描述】:

我需要导入一个文本文件,然后导出一个文本文件,其中的行顺序相反

示例输入:

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

【问题讨论】:

  • 所以你希望最后一行是第一行?因此,您可以将新行附加到 out.txt 的开头,或者存储所有行并在读取后通过迭代它们来写入它们,从 size()-1 开始。

标签: java text reverse


【解决方案1】:

使用 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 中,循环它们并将它们写入输出文件。

【讨论】:

  • 您也可以使用Deque 代替StackArrayDeque 是一种非常有效的实现方式。
猜你喜欢
  • 2022-01-09
  • 2022-12-03
  • 2010-10-19
  • 2017-05-16
  • 2018-06-15
  • 1970-01-01
  • 1970-01-01
  • 2010-09-29
相关资源
最近更新 更多