使用Java从文本文件中逐列提取数据

时间:2013-06-10 17:39:57

标签: java text

我在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");
       }

link:Reading selective column data from a text file into a list in Java

在bove链接下,写入使用以下内容: String [] columns = line.split(“”);

但如何正确使用它,请提供任何暗示或帮助?

2 个答案:

答案 0 :(得分:4)

您可以使用正则表达式来检测更长的空格,例如:

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)
}

答案 1 :(得分:3)

   while((line = b.readLine()) != null) {
      String[] columns = line.split(" ");
      System.out.println("my first column : "+ columns[0] );
      System.out.println("my second column : "+ columns[1] );
      System.out.println("my third column : "+ columns[2] );
   }

现在代替System.out.println,用你的专栏做任何你想做的事。

但我认为您的列由tabs分隔,因此您可能希望使用split("\t")