首页 > 解决方案 > 在java中用数组解析文本文件

问题描述

我必须用字符串数组解析一个文本文件,下面的代码工作正常我需要支持如何在解析文本文件时摆脱字段的标题(G1 & G2 & G3)。

   try (Scanner scan = new Scanner(new File("C:\\Test.txt"))) {               
               
                 String N=null;
                 
                while( scan.hasNextLine() )
                {
                    //scan.skip(Pattern.compile("G1  G2  G3 "));
                    
                    String[] ary = scan.nextLine().split( "\\s+" );           
                    
                    if( ary.length == 3)
                    {
                        if( ary[0].startsWith( "A-" ) )
                            
                            N = ary[0]; 

             System.out.printf( "A-%-5s %5s %5s%n", N, ary[1], ary[2] ); 

2/ 文件样本是:

START

ELEMENT

G1      G2      G3
A-0     FX      0
        FX      1 
A-20    FY      0
        FY      1  
  

谢谢

标签: java

解决方案


您的代码主要工作,但我假设您正在寻找更简单的东西。

真正有用的是Streams和utility类Files,操作类Path,一个比较笼统的概念File

Path path = Paths.get("C:\\Test.txt");

// Data of A-* F* 0:
List<String[]> data = Files.lines(path) // lines(path, charset)
            .map(line -> line.split("\\s+"))
            .filter(arr -> arr.length == 3)
            .filter(arr -> arr[0].startsWith("A-"))
            .collect(Collectors.toList());

仅用于打印:

    Files.lines(path, Charset.forName("Windows-1252"))
            .map(line -> line.split("\\s+"))
                    .filter(arr -> arr.length == 3)
                    .filter(arr -> arr[0].startsWith("A-"))
                    .forEach(arr -> System.out.printf("%-7s %5s %5s%n",
                            arr[0], arr[1], arr[2]));

如果问题是按 G1 分组(空第一列作为重复),那么简单的做法是:

public static void main(String[] args) throws IOException {
    Path path = Paths.get("C:/Develop/Test.txt");
    List<String[]> data = new ArrayList<>();
    AtomicReference<String> g1 = new AtomicReference<>("");
    Files.lines(path) // UTF-8 file
            .map(line -> line.split("\\s+"))
                    .filter(arr -> arr.length == 3)
                    .filter(arr -> arr[0].startsWith("A-")
                            || (arr[0].isEmpty() && !data.isEmpty()))
                    .forEach(arr -> {
                        if (!arr[0].isEmpty()) {
                            g1.set(arr[0]);
                        }
                        System.out.printf("%-7s %5s %5s%n", g1, arr[1], arr[2]);
                        arr[0] = g1.get();
                        data.add(arr);
                    });
    for (String[] ary : data) {
        System.out.println(Arrays.toString(ary));
    }
}

我认为后者是你想要的N。受到

A-0     FX      0
A-0     FX      1 
A-20    FY      0
A-20    FY      1  

推荐阅读