0

(Fixed) I am new to Java (Which you probably will be able to tell by the inefficiency of code) and I am having a problem reading data from a text file.

Here is an example of how I create the file and write my data to the file.

  final String GString = "c:/GradeCalc/java/files";
        Path Gpath = Paths.get(GString);
        if (Files.notExists( Gpath )){
            try {
                Files.createDirectories(Gpath);
            } catch (IOException e2) {

                System.out.println(e2);
            }
        }

        final String Gfile = "Grades.txt";
         Path filePath = Paths.get(GString, Gfile);
         if (Files.notExists (filePath)) {

            try {
                Files.createFile (filePath);
            } catch (IOException e1) {

                System.out.println(e1);
            }
        }

        File gradeFile = filePath.toFile();
        try (PrintWriter out = new PrintWriter(
                new BufferedWriter(
                new FileWriter (gradeFile))))
        {

            if (BQ1Num != null){
            out.print(BQ1Num + "\t" );
            }else{
                out.print("0.0"+"\t");}
            if (BQ2Num != null){
                out.print(BQ2Num + "\t" );
                }else{
                    out.print("0.0"+"\t");}
            if (BQ3Num != null){
                out.print(BQ3Num + "\t" );
                }else{
                    out.print("0.0"+"\t");}
            if (BQ4Num != null){
                out.println(BQ4Num + "\t" );
                }else{
                    out.println("0.0"+"\t");}

                out.close ();
        }
            catch (IOException a)
            {
                System.out.println (a);
                }

Writting the data to the file seems to work perfectly. My problem arrises when I try to read that data and set it to a variable.

Here is an example of how I attempt to read the data from said file and assign the data to variables, then use those variables.

            try (BufferedReader in = new BufferedReader(new FileReader(Gfile))){

                String line = in.readLine();

                while(line != null){
                String[] columns = line.split("\t");
                BQ1RetrievedNum = columns [0];
                BQ2RetrievedNum = columns [1];
                BQ3RetrievedNum = columns [2];
                BQ4RetrievedNum = columns [3];

                 line = in.readLine();
                }
                }

            catch(IOException b){

                System.out.println(b);

            }




    if (BQ1RetrievedNum != null ){
    BQ1.setText("   Quarter 1  " +BQ1RetrievedNum+ "%");
    }
    if (BQ2RetrievedNum != null){
    BQ2.setText("   Quarter 2  " +BQ2RetrievedNum+ "%");
    }
    if (BQ3RetrievedNum != null){
    BQ3.setText("   Quarter 3  " +BQ1RetrievedNum+ "%");
    }
    if (BQ4RetrievedNum != null){
    BQ4.setText("   Quarter 4  " +BQ1RetrievedNum+ "%");
    }

Whenever I run my program, I get an ArrayIndexOutOfBoundsException. I've been searching for hours on how to fix this exception, but with no success.

Here is what the contents of the Grades.txt look like.

43.0 0.0 0.0 0.0

Here is the code for the fileReader that I now have after some editing.

try (BufferedReader in = new BufferedReader(new FileReader(Gfile))){

                String line = in.readLine();
                line = in.readLine();
                  String[]columns = line.split("\t");
                  for(int i=0;i<4;i++) {
                       if(i<columns.length) {
                          switch(i) {
                             case 1:  BQ1RetrievedNum = columns[0];
                                      break;
                             case 2:  BQ2RetrievedNum = columns[1];
                                      break;
                             case 3:  BQ3RetrievedNum = columns[2];
                                    break;
                             case 4:  BQ4RetrievedNum = columns [3];
                                    break;


                       }
                  }
                }
            }


            catch(IOException b){

                System.out.println(b);

            }

I keep getting a NullPointerException on this line:

 String[]columns = line.split("\t");

This is the code for my repaired reader.

 try (BufferedReader reader = Files.newBufferedReader(filePath, ENCODING )){
                  String line = null;
                  while ((line = reader.readLine()) != null) {

                System.out.println(line);
                String[]columns = line.split("/");
                BQ1RetrievedNum = "";
                BQ2RetrievedNum = "";
                BQ3RetrievedNum = "";
                BQ4RetrievedNum = "";

                System.out.println(columns.length);

                for(int i=0;i<4;i++) {
                    if(i<columns.length) {
                       switch(i) {
                          case 0:  BQ1RetrievedNum = columns[0];
                                   break;
                          case 1:  BQ2RetrievedNum = columns[1];
                                   break;
                          case 2:  BQ3RetrievedNum = columns[2];
                                 break;
                          case 3:  BQ4RetrievedNum = columns[3];
                                 break;


                       }
                    }
                }

                System.out.println("1: "+BQ1RetrievedNum);
                System.out.println("2: "+BQ2RetrievedNum);
                System.out.println("3: "+BQ3RetrievedNum);
                System.out.println("4: "+BQ4RetrievedNum);

                  }
                }



            catch(IOException b){

                System.out.println(b);

            }
James Allison
  • 135
  • 10

2 Answers2

3

When you split according to \t:

String[] columns = line.split("\t");

You don't check the length of the returned array. You're getting the exception in one of these lines:

BQ1RetrievedNum = columns [0];
BQ2RetrievedNum = columns [1];
BQ3RetrievedNum = columns [2];
BQ4RetrievedNum = columns [3];

Before doing that, make sure the array has 4 elements.


You can do something like this:

for(int i=0;i<4;i++) {
   if(i<columns.length) {
      switch(i) {
         case 1:  BQ1RetrievedNum = columns[0];
                  break;
         case 2:  BQ2RetrievedNum = columns[1];
                  break;
         //...
      }
   }
}
Maroun
  • 94,125
  • 30
  • 188
  • 241
  • I am getting the excetion in BQ2retrievedNum = columns[2]; My array only has one element. How can I fix that? – James Allison Oct 22 '13 at 12:56
  • You can have an `if` before you try to access this element. – Maroun Oct 22 '13 at 13:06
  • (Correction, the exception is in BQ2retrievedNum = columns[1]) I tried to add an `if` statement, and it didn't seem to help. Could you give me an example of what you mean? – James Allison Oct 22 '13 at 13:21
  • I am having difficulty understanding how the code works and how to use it in my existing code. Sorry for the inconvenience. – James Allison Oct 22 '13 at 13:57
1

See what is the length of the array

System.out.println(columns.length);

It may not contains expected number of values

EDIT: Following code work for me. Case values are edited.

String line = "43.0 0.0 0.0 0.0";
    String[]columns = line.split("\t");
    String output1 = "";
    String output2 = "";
    String output3 = "";
    String output4 = "";

    System.out.println(columns.length);

    for(int i=0;i<4;i++) {
        if(i<columns.length) {
           switch(i) {
              case 0:  output1 = columns[0];
                       break;
              case 1:  output2 = columns[1];
                       break;
              case 2:  output3 = columns[2];
                     break;
              case 3:  output4 = columns[3];
                     break;
           }
        }
    }

    System.out.println("1: "+output1);
    System.out.println("2: "+output2);
    System.out.println("3: "+output3);
    System.out.println("4: "+output4);

String.split("") doesn't throw NullPointerException

Isuru Gunawardana
  • 2,847
  • 6
  • 28
  • 60
  • I did as you suggested and my array only has one element. I am now trying to figure out how to fix that. – James Allison Oct 22 '13 at 12:57
  • Thank you, that solved many of my proplems. Now I have some other problems to work out. The method in.readLine is reading the files contents as one of my variables, Num, not the actual line. – James Allison Oct 22 '13 at 19:31
  • The `in.readLine` does not read the contents of Grade.txt as "43.0/0.0/0.0/0.0/". Everything else works perfectly. Do you know what could be wrong? – James Allison Oct 22 '13 at 20:05
  • @user2905618 have a look here http://stackoverflow.com/questions/4716503/best-way-to-read-a-text-file And be generous to accept an answer as the answer or upvote the answers if they are help full. – Isuru Gunawardana Oct 23 '13 at 03:57
  • 1
    Thank you for your help. Thanks to you and @Maroun Maroun I figured out how to fix it. – James Allison Oct 23 '13 at 04:31