【问题标题】:extract data column-wise from text file using Java使用Java从文本文件中按列提取数据
【发布时间】:2013-06-10 17:39:57
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: java text


    【解决方案1】:

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

    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 行,即 row[1] 用在哪里? System.out.println(Arrays.toString(row[1]));显示错误,怎么用???
    • Arrays.toString() 是显示一个数组,row[1] 是一个字符串,所以它不起作用,你必须改变它。编辑了答案,看看吧。
    【解决方案2】:
       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")

    【讨论】:

    • 在他的情况下“”不是分隔符
    猜你喜欢
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多