[英]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.