Java read values from text file

后端 未结 2 1865
-上瘾入骨i
-上瘾入骨i 2021-01-12 10:44

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.263         


        
2条回答
  •  长发绾君心
    2021-01-12 10:57

    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());
    }
    

    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;
    }
    

    Hope this helps. I would still highly recommend reading the Java I/O and String tutorials.

提交回复
热议问题