簡體   English   中英

從txt文件java中讀取特定行

[英]read specific line from txt file java

我有個問題! 我有一個txt文件(在不移動的特定路徑中),其中包含內容可變的字符串。 我必須使用此字符串輸入我的算法。 txt文件的解決方案示例是

50 [40,-13,-6,-7,-4] [28,-40,45,-29,37] [-43,19,-24,-9,-45] [26,-41,-28,-16,44]

要么

4 [-3,-1,2] [-2,-4,1] [-3,2,1] [-2,3,-4] [4,2,1] [4,-1,2] [3,-4,1] [-3,-2,-4] 

我必須使用括號內的數字50或4或另一個數字作為整數。 但所有其他內容必須提取為特定的字符串,然后再傳遞給方法。 有人有解決方案嗎? 重要說明:文件的內容是可變的

如果/Application/testdata/ntd.txt是您txt文件的路徑,則下面的代碼將起作用(我想您的要求是)。

public static void main(String[] args) throws IOException 
    {

        String content=null;
        File folder = new File("/Application/testdata/ntd.txt");

              content = FileUtils.readFileToString(folder)+"\n";
              System.out.println(content);


        int outside=Integer.parseInt(content.substring(0, content.indexOf("[")).trim());
        System.out.println("int val: "outside);
        String remainingString=content.substring(content.indexOf("["), content.lastIndexOf("]")+1);
        System.out.println("String value: "remainingString);
    }

輸出:

  50 [40,-13,-6,-7,-4] [28,-40,45,-29,37] [-43,19,-24,-9,-45] [26,-41,-28,-16,44]
  int val: 50
  String value: [40,-13,-6,-7,-4] [28,-40,45,-29,37] [-43,19,-24,-9,-45] [26,-41,-28,-16,44]

我使用apache commons進行文件讀取。 如果您想進一步破壞remainingString字符串,則根據空格字符將其拆分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM