簡體   English   中英

我想從文件中的一行讀取數據。 在Java中

[英]I want to read data from a line in a file. in Java

我目前正在嘗試從java中的多行(來自指定文件)讀取某些數據。

例如,下面的行我想存儲數組中每行的數值,我不想將整行讀入數組(我已經可以這樣做了)

      Firstname 100700 Lastname
      Firstname 260000 Lastname
      Firstname 303000 Lastname
      Firstname 505050 Lastname

我將如何在我的代碼中放置一些東西,允許程序在我的場景中讀取數值數據。(順便說一下空間應該在那里)BufferedReader輸入;

    input = new BufferedReader(new FileReader("file.txt"));// file to be read from
    String Line;
    int i = 0;
    int[]number=new int[4];
    while (Line != null)
    {
        Line = input.readLine(); 

       // Then i would need something down here to read the numerical values?
        number[i]=????

        i++
    }

任何幫助,將不勝感激。

謝謝。

看看String.split()Integer.parseInt() Hava。

您可以使用Line.split(" ")String拆分為String[] ,然后使用Integer.parseInt(myArray[1])將數字作為int

另請注意:在java中,約定是變量以小寫字母開頭,因此您應該考慮重命名Line - > line

input = new BufferedReader(new FileReader("file.txt"));// file to be read from
String line;
int i = 0;
int[]number=new int[4];
while (line != null)
{
    line = input.readLine(); 
    // here is my refinement
    String[] x = line.Split();
    System.out.println("FirstName: " + x[0]);
    System.out.println("Number: " + x[1]);
    System.out.println("LastName: " + x[2]);

    i++
}

嘗試這個

String line = input.readLine();
if (line != null) {
   int number = Integer.parseInt(line.replaceAll("[^\\d]", ""));
   ...
}

Scanner具有.hasNextInt().nextInt() 您可以使用它們來讀取數字。 否則你可以在Pattern類中使用一些正則表達式,或者使用amit的建議。

暫無
暫無

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

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