gpt4 book ai didi

java - 如何从android中的文本文件中提取子字符串?

转载 作者:行者123 更新时间:2023-11-29 03:59:28 29 4
gpt4 key购买 nike

我想知道如何从 android 中的文本文件中提取子字符串:

文本文件如下图所示:

[start_delimeter]

0|1|text1

0|1|text2

0|1|text3

0|1|text4

[end_delimiter]

我想提取 start_delimeter 和 end_delimiter 之间的字符串。

我怎样才能用 java 语言/android 做到这一点??

最佳答案

序列:

  • 首先,您需要将文本文件放入 Assets 目录(例如 filename.txt)
  • 读取文件(使用 BufferedReader)直到读取开始分隔符
  • 从文件中读取每一行并使用 PatternMatcher 处理它直到找到结束分隔符(或使用 String.split("|") )

这是代码:

    // first get the file from the assets
InputStream is = context.getAssets().open("filename.txt");

try {
// start reading (line by line)
BufferedReader r = new BufferedReader(new InputStreamReader(is));

// wait for the start delimiter
String line;
while ((line = r.readLine()) != null)
if (line.equals("[start_delimiter]"))
break;

// this is the pattern for the data "int|int|String":
Pattern p = Pattern.compile("\\|(\\d+)\\|(\\d+)\\|(.+)");

// read it line by line...
while ((line = r.readLine()) != null) {
// ... till the end comes (end delimiter)
if (line.equals("[end_delimiter]"))
break; //done

// if the data matches the pattern...
Matcher m = p.matcher(line);
if (m.matches()) {
// ... handle it!
int first = Integer.parseInt(m.group(1));
int second = Integer.parseInt(m.group(2));
String text = m.group(3);

//...
}
}

} finally {
is.close();
}

关于java - 如何从android中的文本文件中提取子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4380011/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com