亚洲视频二区_亚洲欧洲日本天天堂在线观看_日韩一区二区在线观看_中文字幕不卡一区

公告:魔扣目錄網為廣大站長提供免費收錄網站服務,提交前請做好本站友鏈:【 網站目錄:http://www.430618.com 】, 免友鏈快審服務(50元/站),

點擊這里在線咨詢客服
新站提交
  • 網站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會員:747

本文介紹了顛倒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中,循環(huán)遍歷它們并將它們寫出到輸出文件中。

這篇關于顛倒txt文件的行序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,

分享到:
標簽:txt 文件 顛倒
用戶無頭像

網友整理

注冊時間:

網站:5 個   小程序:0 個  文章:12 篇

  • 51998

    網站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會員

趕快注冊賬號,推廣您的網站吧!
最新入駐小程序

數獨大挑戰(zhàn)2018-06-03

數獨一種數學游戲,玩家需要根據9

答題星2018-06-03

您可以通過答題星輕松地創(chuàng)建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學四六

運動步數有氧達人2018-06-03

記錄運動步數,積累氧氣值。還可偷

每日養(yǎng)生app2018-06-03

每日養(yǎng)生,天天健康

體育訓練成績評定2018-06-03

通用課目體育訓練成績評定