基于列(Java)的字符串拆分

时间:2014-11-20 20:52:18

标签: java string text format

java新手。我想在一个文件中读取具有这样格式的行

en Fox 3 1344
en Bird 19 144
en Dog 93 1234

对于每一行,我想选择第2列和第3列的内容。在第一行“Fox”和“3”的情况下。并显示它们。到目前为止,这就是我所拥有的。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class pagecounts {

   public static void main(String[] args) throws FileNotFoundException {

       String content = new Scanner(new File("filename")).useDelimiter("\\Z").next();

            *// letter in column 2 and 3 pick code goes here.*

        System.out.println(content);

   }
 }

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

假设每列只能包含一个值(字/数字),您可以使用扫描仪从一行读取所有标记,并仅使用您感兴趣的标记。

try(Scanner sc = new Scanner(new File(path))){//try-with-resources
                                    //will automatically close stream to file
    while (sc.hasNext()){
        String col1 = sc.next();
        String col2 = sc.next();
        int col3 = sc.nextInt();//you can also use next() if you want to get this token as String
        int col4 = sc.nextInt();//same here

        System.out.printf("%-15s %d%n", col2, col3);
    }
}

您还可以逐行读取文件并在空格上分割每行

try(Scanner sc = new Scanner(new File(path))){//try-with-resources
                                    //will automatically close stream to file
    while (sc.hasNextLine()){
        String line = sc.nextLine();
        String[] tokens = line.split("\\s+");//I assume there are no empty collumns
        System.out.printf("%-15s %s%n",tokens[1],tokens[2]);
    }
}

您还可以将此文件视为CSV文件(逗号分隔值),其中值以空格分隔。要解析此类文件,您可以使用OpenCSV等库,其中分隔符定义为空格

try(CSVReader reader = new CSVReader(new FileReader(path),' ')){
    String[] tokens = null;                           //   ^--- use space ' ' as delimiter
    while((tokens = reader.readNext())!=null)
        System.out.printf("%-15s %s%n",tokens[1],tokens[2]);
} catch (IOException e) {
    e.printStackTrace();
}

答案 1 :(得分:0)

使用split

 System.out.println(content.split(" ")[1] + " " + content.split(" ")[2]);