Java - Parsing Text File

Deadly 提交于 2019-12-29 07:56:11

问题


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.


回答1:


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



回答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
}


来源:https://stackoverflow.com/questions/5819772/java-parsing-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!