2011-05-11 138 views
6

我是Java的新手。我有一个文本文件,内容如下。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

“为两个不同”?你需要尝试更清楚地解释你想要的。也许在此期间,[Java I/O教程](http://download.oracle.com/javase/tutorial/essential/io/)可能对您有用。 – 2011-05-11 08:38:29

+1

两个不同的...列表? :) – 2011-05-11 08:39:57

+0

请更具体一点。什么是和什么是B? – 2011-05-11 08:40:49

回答

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

你可以玩分裂。首先在文本中找到与“a”(或“b”)匹配的行。然后做这样的事情:

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

然后:

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

您将有数字的ArrayList中的[]。请小心最后的括号)),因为他们之后有一个“,”。但这是代码净化,这是你的使命。我给了你这个想法。