反转txt文件的行顺序

问题描述 投票:0回答:2

我需要导入文本文件并以相反的顺序导出文本文件,其行数相反

示例输入:

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 text reverse
2个回答
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);
    }

}

只需读取输入文件并在StringFiles#lines)中获取其内容流。然后使用降序的迭代器将它们收集到LinkedList中,对其进行循环,然后将其写到输出文件中。


0
投票

以下是我能想到的最简单的答案,使用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);
    }

}

只需读取输入文件并在StringFiles#lines)中获取其内容流。然后使用降序的迭代器将它们收集到LinkedList中,对其进行循环,然后将其写到输出文件中。

© www.soinside.com 2019 - 2024. All rights reserved.