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

link:将选择列数据从文本文件读入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) } 
  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")代替。