从文本文件中读取Java值

7
我刚开始学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))
 )
)
  
现在我想要的是,把"a"和"b"作为两个不同的数组列表。

4
“as two different”是什么意思,你需要尽量清楚地解释你想要的是什么。也许在此期间,Java I/O教程可以对您有所帮助。 - Joachim Sauer
请具体说明一下。a和b分别是什么? - Jav_Rock
1
你想要对Java对象进行序列化和反序列化吗? - vinothkr
如果那是一个文本文件,你可以使用FileReader并使用split(""")来匹配包含"a"和"b"的行。你是指这样的意思吗? - Jav_Rock
文件的结构是否保持不变?如果是,那么您可以使用BufferedInputStream并解析字符串来创建数组。 - Ankit
是的,确切地说。您能否为我提供一个示例代码? - Tapsi
2个回答

7

您需要逐行读取文件。可以使用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());
}

假设您的文件中的 "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;
}

希望这能有所帮助。我仍然强烈建议阅读Java的I/OString教程。


2

你可以使用split方法。首先找到文本中与 "a"(或 "b")匹配的行。然后执行类似于以下内容的操作:

Array[] first= line.split("("); //first[2] will contain the values

然后:

Array[] arrayList = first[2].split(",");

你将在arrayList[]中获得数字。要注意最后的括号)), 因为它们紧跟着一个逗号。但这是代码调试的任务,我给了你思路。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接