简体   繁体   English

从多行文本文件中获取整数向量

[英]Get an integer vector from a multi-line text file

I need to parse a .txt file to three double arrays. 我需要将.txt文件解析为三个双数组。 This files has various lines. 这个文件有各种各样的行。 In each line there are three integes divided by space. 在每一行中有三个整数除以空格。

Example: 例:

19.1    24.3    0
18.2    24.0    0
12.6    24.9    20
14.4    28.0    20

My goal is to get three double array ( x , y and z ) and in each array there should be a column. 我的目标是获得三个双数组( xyz ),并且在每个数组中应该有一列。 So the result should be the same of writing the following instructions: 因此,结果应与编写以下说明相同:

double[] x = {19.1,18.2,12.6,14.4};
double[] y = {24.3,24.0,24.9,28.0};
double[] z = {0,0,20,20};

I know how to open and read files, something like this: 我知道如何打开和读取文件,如下所示:

String file = "filename.txt";
String line=null;
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while(!(line=br.readLine()).contains("EOF")) {
  // read and process one line..
}

What I don't know how to do is how to parse each number of the current line and assign it to one of the three vectors. 我不知道该怎么做是如何解析当前行的每个数字并将其分配给三个向量之一。

You can simply split and parse each line as follows: 您可以按如下方式简单地拆分和解析每一行:

String[] row = line.split("\\s+");
double d1 = Double.parseDouble(row[0]);
double d2 = Double.parseDouble(row[1]);
double d3 = Double.parseDouble(row[2]);

Also, if the number of lines is not fixed then it will be easier and makes more sense to use ArrayList s of Double s instead of arrays of double s. 此外,如果行数没有固定,那么使用Double s的ArrayList而不是double的数组会更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM