Question

i have a question! I have a txt file (in a specific path that don't move) that contains a string which content is variable. i must use this string for input of my algorithm. A example of solution of txt file is

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

or

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] 

I must use the number 50 or 4 or another number out of brackets as a int. but all the rest of the content must be extracted in a particular string that after will pass to a method. anyone have a solution? IMPORTANT: the contents of the file is variable

Was it helpful?

Solution

If /Application/testdata/ntd.txt is the path of your txt file then below code will work (what i guess is your requirement).

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);
    }

OUTPUT:

  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]

I used apache commons for file read. If you waNT to break remainingString further then split it according to SPACE character.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top