4

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.

4
  • What is the problem with Scaner? Commented Apr 28, 2011 at 13:57
  • Can you paste the code you wrote? Commented Apr 28, 2011 at 13:58
  • No code to post. My original thought was to save each line into a string but since the total number to dep's is unknown it would need some sort of loop correct? Commented Apr 28, 2011 at 13:59
  • 1
    Read the file line by line... split each line on ':' then the first part is the target, and then the second part is all the deps, which can be separated by splitting on space Commented Apr 28, 2011 at 14:00

2 Answers 2

11
  • 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]);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Load each line into its own string? Or use while(hasNextLine)? I understand the splitting and iterate but how would each line become it's own string?
I've just provided this info :)
I understand it now. Thanks for posting.
added the FileReader and loop.
2

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
}

1 Comment

where should the file be stored? in the project folder or src folder?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.