簡體   English   中英

如何讀取文件並按行拆分文本?

[英]How to read a file and split the text by each line?

我需要閱讀一個看起來像這樣的文本文件

8 7
~~~~~~~
~~~~~~~
B~~~~~~
~~~~~~~
~~~~B~~
~~~~B~~
~~~~~~B
~~~~~~~
~~~~~~~

我的程序正在重新創建戰艦游戲。 我需要接受值8和7,但只能從第二行開始打印。 我應該使用string.split(我相信)。 我只需要打印帶有〜和B的行。 我已經有讀取文件的代碼,只是不確定如何通過換行符分割文件。

File file = new File(args[1]);
    try 
        {
        Scanner sc = new Scanner(file);
        while (sc.hasNextLine()) 
            {
            String themap = sc.nextLine();          
            System.out.println(themap); 
            }
        sc.close();
        } 
    catch (Exception e) 
        {
        System.out.println("ERROR: File does not exist");
        }

您已經在使用sc.nextLine()逐行讀取它。 它將逐行讀取文件。 無需使用split來獲取每一行。 為了證明更改您的println語句以向您知道的每一行添加內容,這不在文件中。

System.out.println( "Yaya " + themap );

如果在運行程序時在每一行的前面看到Yaya,則說明您正在逐行讀取它,並且在每次循環時,map都指向文件外的一行。

之后,您只需要在該行中搜索以找到B和8,然后將它們提取到另一個數據結構中即可。 有很多方法可以做到這一點,但是請檢查String api,以獲取有助於解決問題的方法。

使用Java 8 PathsPathFiles.readAllLines和流(輸入在/tmp/layout.txt ):

package stackoverflow;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class StackOverflow {

    public static void main(String[] args) throws IOException {
        Path layout = Paths.get("/tmp", "layout.txt");
        List<String> lines = Files.readAllLines(layout);
        lines.remove(0); // Don't print the first line.
        lines.stream().forEach(System.out::println);
    }
}

如果您不能使用Java 8,請使用

for (String line : lines) {
    System.out.println(line);
}

代替

lines.stream().forEach(System.out::println);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM