使用Java从文本文件中逐列提取数据
我在Java下工作,想根据文本文件中的列提取数据。
“ myfile.txt”内容:
    ID     SALARY RANK      065    12000   1
    023    15000   2
    035    25000   3
    076    40000   4
我想根据任何列分别提取数据,即ID,SALARY,RANK等。
基本上,我想根据列对单个数据执行操作。
我通过使用while循环并逐行读取列出了“ myfile.txt”中的数据:
    while((line = b.readLine()) != null) {          stringBuff.append(line + "\n");
       }
链接:将文本文件中的选择性列数据读入Java列表中
在bove链接下,使用以下代码编写:String [] columns = line.split(“”);
但是如何正确使用它,请提供任何提示或帮助?
回答:
您可以使用正则表达式来检测更长的空格,例如:
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从文本文件中逐列提取数据 的全部内容, 来源链接: utcz.com/qa/402068.html








