Java,从文件获取特定的字符串

时间:2018-09-18 17:12:55

标签: java

我想从文本文件中获取特定的字符串。

例如,我只希望将指示的部分(第三行)保存到新文件中

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中,但是现在我该怎么办

  1. 仅保存此ArrayList的一个元素
  2. 仅将行的一部分(粗体显示)保存在变量或新文件中。

编辑 我解决了所有问题非常感谢您特别感谢@dustytrash

1 个答案:

答案 0 :(得分:-1)

您检查每一行以查看其是否包含所需的值。找到该值后,您可以停止扫描(假设您只寻找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);
}