Java read values from text file

后端 未结 2 1850
-上瘾入骨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.

    0 讨论(0)
  • 2021-01-12 11:09

    You can play with split. First find the line in the text that matches "a" (or "b"). Then do something like this:

    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.

    0 讨论(0)
提交回复
热议问题