java - 在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
谢谢
解决方案
您的代码主要工作,但我假设您正在寻找更简单的东西。
真正有用的是Stream
s和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
推荐阅读
- java - 与 apache derby 数据库中任意数量的字段建立一对多关系的最佳方法是什么?
- swift - 将数据传递给 iOS UIViewController 的问题
- javascript - 从我自己的服务器获取,错误:“JSON 输入意外结束”
- javascript - 请建议 JQuery 方法
- elixir - 使用 Phoenix EEX 模板时如何在 Gettext 字符串中嵌入链接?
- java - 使用多个 api 请求和一个适配器将数据显示到回收器视图中
- android - 在 Recyclerview 中请求超过 5 个原生广告 - Admob
- awk - nf的多个选项用于识别不同位置awk中的重复项?
- mongodb - 根据在 Mongo Atlas 中创建的索引在前端创建 MongoDB 索引
- android - 状态展开的底片圆角