[英]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:我需要得到这个解析来用每个目标和 dep 调用我的方法,例如:
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?在文本文件的每一行上调用
function(target,dep)
的最有效方法是什么? I tried fooling around with the scanner and string.split but was unsuccessful.我试着用扫描仪和 string.split 鬼混,但没有成功。 I'm stumped.
我难住了。
Thanks.谢谢。
String myLine
String myLine
myLine
on :
into String[] array1
myLine
on :
拆分为String[] array1
array1[1]
on ' '
into String[] array2
' '
上的array1[1]
拆分为String[] array2
array2
and call function(array1[0], array2[i])
array2
并调用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]);
}
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.