Search code examples
javafile-iobufferedreaderfileinputstream

Reading data in Java from text


I'm trying to read the ex2data2.txt which contains dataset with 3 columns. I want to store it in my x array and y array. but it is not working. it cannot read the text file. the location of text file is in my src folder along with my codes.

    double[][] x = new double[180][1];
    double[][] y = new double[180][0];
       try{
           BufferedReader br=new BufferedReader(new FileReader("ex2data2.txt"));
           String words[]=new String[2];
           String line=null;
           int i = 0;
           while((line=br.readLine())!=null){
               words=line.split(",");
               //double[i] y = Double.parseDouble(words);
                x[i][0] = Double.parseDouble(words[0]);
                x[i][1] = Double.parseDouble(words[1]);
                y[i][0] = Double.parseDouble(words[2]);
           i++;
           }
           br.close();
       }
       catch(Exception e){
           System.err.println("Error: Target File Cannot Be Read");
       }

Solution

  • You should put the file in the top, parent project folder. not in src/.

    Edit : I have run this, for proof...

    Accessing file, read all the data.

    java.lang.NumberFormatException: For input string: "43 323 33" this I have put in that file

    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
    at java.lang.Double.parseDouble(Double.java:540)
    at com.rem.so.Rem.main(Rem.java:18)
    

    Next run

    java.lang.ArrayIndexOutOfBoundsException: 1
        at com.rem.so.Rem.main(Rem.java:19)
    

    After correcting this..

    double[][] x = new double[180][2];
    double[][] y = new double[180][1];
    

    it is now done.

    Please find the screenshot where I have put the file...

    enter image description here