Java从文本文件中读取值 [英] Java read values from text file
本文介绍了Java从文本文件中读取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Java新手。我有一个文本文件,内容如下。
I am new to Java. I have one text file with below content.
`trace` -
structure(
list(
"a" = structure(c(0.748701,0.243802,0.227221,0.752231,0.261118,0.263976,1.19737,0.22047,0.222584,0.835411)),
"b" = structure(c(1.4019,0.486955,-0.127144,0.642778,0.379787,-0.105249,1.0063,0.613083,-0.165703,0.695775))
)
)
现在我想要的是,我需要将a和b作为两个不同的数组列表。
Now what I want is, I need to get "a" and "b" as two different array list.
推荐答案
你需要逐行读取文件。它是用 BufferedReader
完成的,如下所示:
You need to read the file line by line. It is done with a BufferedReader
like this :
try {
FileInputStream fstream = new FileInputStream("input.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int lineNumber = 0;
double [] a = null;
double [] b = null;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
lineNumber++;
if( lineNumber == 4 ){
a = getDoubleArray(strLine);
}else if( lineNumber == 5 ){
b = getDoubleArray(strLine);
}
}
// Close the input stream
in.close();
//print the contents of a
for(int i = 0; i < a.length; i++){
System.out.println("a["+i+"] = "+a[i]);
}
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
假设你的a
和b
位于文件的第四行和第五行,需要在满足这些行时调用方法,该方法将返回<$ c的数组$ c> double :
Assuming your "a"
and"b"
are on the fourth and fifth line of the file, you need to call a method when these lines are met that will return an array of double
:
private static double[] getDoubleArray(String strLine) {
double[] a;
String[] split = strLine.split("[,)]"); //split the line at the ',' and ')' characters
a = new double[split.length-1];
for(int i = 0; i < a.length; i++){
a[i] = Double.parseDouble(split[i+1]); //get the double value of the String
}
return a;
}
希望这会有所帮助。我仍然强烈建议您阅读Java I / O 和字符串教程。
Hope this helps. I would still highly recommend reading the Java I/O and String tutorials.
这篇关于Java从文本文件中读取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文