这个问题在这里已有答案:
我想从Text文件中获取特定的String。
例如,我只希望将指定的部分(第3行)保存在新文件中
19:22:08.999 T:5804 NOTICE: Aero is enabled
19:22:08.999 T:5804 NOTICE: special://xbmc/ is mapped to: C:\Program Files (x86)\Kodi
19:22:08.999 T:5804 NOTICE: key://xbmcbin/ is mapped to: C:\Program Files (x86)\Kodi
I want this part -----> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
19:22:08.999 T:5804 NOTICE: special://xbmcbinaddons/ is mapped to: C:\Program Files (x86)\Kodi/addons
我的代码:
public static void main(String[] args) throws IOException {
ArrayList<String> result = new ArrayList<>();
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("C:/test.txt")));
while (s.hasNextLine()) {
result.add(s.nextLine());
}
} finally {
if (s != null){
s.close();
}
} System.out.println(result);
}
我把所有东西保存在一个ArrayList中,但我现在怎么样
编辑我解决了一切非常感谢你的帮助,特别是@dustytrash
您检查每一行以查看它是否包含您需要的值。当您找到该值时,您可以停止扫描(假设您只需要查找1行)。然后,您可以根据需要解析该行。
根据您的示例,以下生成的'key:// xbmcbin /映射到:C:\ Program Files(x86)\ Kodi':
public static void main(String[] args) throws IOException
{
String result = "";
Scanner s = null;
try
{
final String searchKey = "key:";
final String trimFromLine = "Kodi";
s = new Scanner(new BufferedReader(new FileReader("test.txt")));
while (s.hasNextLine() && result.isEmpty())
{
String nextLine = s.nextLine();
if (nextLine.contains(searchKey))
{
// Trim everything from the end, to the beginning character of our searchKey (in this case 'key:')
result = nextLine.substring(nextLine.indexOf(searchKey));
// Take everything from the beginning to the end of the beginning character in our trimFromLine (in the case start index of 'Kodi')
result = result.substring(0, result.indexOf(trimFromLine));
}
}
}
finally
{
if (s != null)
{
s.close();
}
} System.out.println(result);
}