Java - Parsing Text File

前端 未结 2 529
孤街浪徒
孤街浪徒 2020-12-19 16:10

I have an input text file in this format:

 :   ...
 :   ...
...
相关标签:
2条回答
  • 2020-12-19 16:18
    • Read line into String myLine
    • split myLine on : into String[] array1
    • split array1[1] on ' ' into String[] array2
    • Iterate through array2 and call function(array1[0], array2[i])

    So ...

    FileReader input = new FileReader("myFile");
    BufferedReader bufRead = new BufferedReader(input);
    String myLine = null;
    
    while ( (myLine = bufRead.readLine()) != null)
    {    
        String[] array1 = myLine.split(":");
        // check to make sure you have valid data
        String[] array2 = array1[1].split(" ");
        for (int i = 0; i < array2.length; i++)
            function(array1[0], array2[i]);
    }
    
    0 讨论(0)
  • 2020-12-19 16:25

    The firstly you have to read line from file and after this split read line, so your code should be like:

    FileInputStream fstream = new FileInputStream("your file name");
    // or using Scaner
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    //Read File Line By Line
    while ((strLine = br.readLine()) != null)   {
      // split string and call your function
    }
    
    0 讨论(0)
提交回复
热议问题