使用Java从文本文件中逐列提取数据 [英] extract data column-wise from text file using Java
问题描述
我在Java下工作并希望根据文本文件中的列提取数据。
myfile.txt内容:
I'm working under Java and want to extract data according to column from a text file.
"myfile.txt" contents:
ID SALARY RANK
065 12000 1
023 15000 2
035 25000 3
076 40000 4
我想根据任何列分别提取数据,即ID,SALARY,RANK等
基本上我想要执行根据列对单个数据进行操作。
I want to extract the data individually according to any Column i.e ID, SALARY, RANK etc
Basically I want to perform operations on individual data according to columns.
我通过使用while循环并逐行读取来列出myfile.txt中的数据:
I've listed the data from "myfile.txt" by using while loop and reading line-by-line:
while((line = b.readLine()) != null) {
stringBuff.append(line + "\n");
}
link:将选择性列数据从文本文件读入Java列表
在bove链接下,编写使用以下内容:
String [] columns = line.split();
Under bove link it is written to use the following: String[] columns = line.split(" ");
但如何正确使用它,请提供任何提示或帮助?
But how to use it correctly, please any hint or help?
推荐答案
您可以使用正则表达式来检测更长的空格,例如:
You can use a regex to detect longer spaces, example:
String text = "ID SALARY RANK\n" +
"065 12000 1\n" +
"023 15000 2\n" +
"035 25000 3\n" +
"076 40000 4\n";
Scanner scanner = new Scanner(text);
//reading the first line, always have header
//I suppose
String nextLine = scanner.nextLine();
//regex to break on any ammount of spaces
String regex = "(\\s)+";
String[] header = nextLine.split(regex);
//this is printing all columns, you can
//access each column from row using the array
//indexes, example header[0], header[1], header[2]...
System.out.println(Arrays.toString(header));
//reading the rows
while (scanner.hasNext()) {
String[] row = scanner.nextLine().split(regex);
//this is printing all columns, you can
//access each column from row using the array
//indexes, example row[0], row[1], row[2]...
System.out.println(Arrays.toString(row));
System.out.println(row[0]);//first column (ID)
}
这篇关于使用Java从文本文件中逐列提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!