繁体   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