Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Parsing Text File

I have an input text file in this format:

<target1> : <dep1> <dep2> ...
<target2> : <dep1> <dep2> ...
...

And a method that takes two parameters

function(target, dep);

I need to get this parsing to call my method with each target and dep eg:

function(target1, dep1);
function(target1, dep2);
function(target1, ...);
function(target2, dep1);
function(target2, dep2);
function(target2, ...);

What would be the most efficient way to call function(target,dep) on each line of a text file? I tried fooling around with the scanner and string.split but was unsuccessful. I'm stumped.

Thanks.

like image 752
Mike Avatar asked Dec 13 '22 13:12

Mike


2 Answers

  • 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]);
}
like image 77
Brian Roach Avatar answered Dec 28 '22 10:12

Brian Roach


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
}
like image 36
jitm Avatar answered Dec 28 '22 11:12

jitm