Java 从文本文件中读取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5961440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java read values from text file
提问by Tapsi
I am new to Java. I have one text file with below content.
我是 Java 新手。我有一个包含以下内容的文本文件。
`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)) ) )
Now what I want is, I need to get "a" and "b" as two different array list.
现在我想要的是,我需要将“a”和“b”作为两个不同的数组列表。
采纳答案by krookedking
You need to read the file line by line. It is done with a BufferedReader
like this :
您需要逐行读取文件。它是通过这样的方式完成的BufferedReader
:
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());
}
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
:
假设您的"a"
和"b"
位于文件的第四行和第五行,您需要在遇到这些行时调用一个方法,该方法将返回一个数组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;
}
Hope this helps. I would still highly recommend reading the Java I/Oand Stringtutorials.
回答by Jav_Rock
You can play with split. First find the line in the text that matches "a" (or "b"). Then do something like this:
你可以玩分裂。首先在文本中找到与“a”(或“b”)匹配的行。然后做这样的事情:
Array[] first= line.split("("); //first[2] will contain the values
Then:
然后:
Array[] arrayList = first[2].split(",");
You will have the numbers in arrayList[]. Be carefull with the final brackets )), because they have a "," right after. But that is code depuration and it is your mission. I gave you the idea.
您将拥有 arrayList[] 中的数字。小心最后的括号 )),因为它们后面有一个“,”。但那是代码净化,这是您的使命。我给了你这个主意。