簡體   English   中英

讀取文件中每行的第一個字符

[英]Read first character on each line in a file

我有這種格式的文件:

0 2 4
3 2 4
3 5 2
1 8 2

我的目標是讀取每個文件的第一行並將其存儲在一個數組中。 所以最后我應該有0,3,3,1

我認為有一種方法,讀取直到我們遇到一個空格並將其保存在一個數組中...但它會繼續讀取2和4之后

有沒有一種有效的方法,我的鱈魚如下所示:

openandprint()
{
int i = 0;
try (BufferedReader br = new BufferedReader(new FileReader("final.txt"))) 
    {
        String line;
        while ((line = br.readLine()) != null) {
        int change2Int=Integer.parseInt(line.trim());
        figures [i] = change2Int;
        i++;
        }
    }
catch (Exception expe)
    {
    expe.printStackTrace();
    }

}

使用Scanner可以使代碼更清晰:

private static openandprint() throws IOException {
    int i = 0;
    try (Scanner s = new Scanner("final.txt")))  {
        String line;
        while (s.hasNextLine()) {
            int change2Int = s.nextInt();
            s.nextLine(); // ignore the rest of the line
            figures [i] = change2Int;
            i++;
        }
    }
}

嘗試

int change2Int=Integer.parseInt((line.trim()).charAt(0)-'0');

要么

int change2Int=Character.getNumericValue(line.charAt(0));

使用你的approch,你正在讀取整行並將其解析為int,這將給你NumberFormatException因為數字之間的空格。

BufferedReader br = ...;
String line = null;
while ((line = br.readLine()) != null) {
  String[] parts = line.split(" ");
  int next = Integer.parseInt(parts[0]);
  System.out.println("next: " + next);
}

暫無
暫無

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

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