0

I got ArrayIndexOutOfBoundsException: 1 at this line String name = pieces[1]; in the following function:

public static void loadFile() throws FileNotFoundException, IOException {
        file = new File("C:\\Users\\DELL\\OneDrive - Philadelphia University\\Desktop\\NetBeansProjects\\CaloriesIntakeApp\\src\\main\\webapp\\WEB-INF\\data\\data.txt");
      
        try (BufferedReader inputStream = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = inputStream.readLine()) != null) {

                String[] pieces = line.split(" ");

                String id = pieces[0];
                String name = pieces[1];
                int grms = Integer.parseInt(pieces[2]);
                int calories = Integer.parseInt(pieces[3]);
                String photo = pieces[4];

                Fruit f = new Fruit(id, name, grms, calories, photo);

                fruitList.add(f);

            }
        }
    }

Need to know the reason!

Shahed A.
  • 17
  • 4
  • `System.out.println( line )` for every line you read and trace it, one of the lines must be without any empty space inside – Nour Alhadi Mahmoud Jun 18 '21 at 14:17
  • Because the line you split did not split into an Array with more than 1 value. When you tried to access the Array with an index greater than the Array's size it threw an error. Check your data to confirm it's all formatted to split correctly with this code. – Tim Hunter Jun 18 '21 at 14:17
  • Not to be snide, but the answer is actually: "because the array index is out of bounds". Try printing out the elements of the `pieces` array to see what data you're *actually* getting. – Silvio Mayolo Jun 18 '21 at 14:18
  • To make debugging which data is causing the problem easier, add something like `if( pieces.length < 5 ) { System.err.println( "Bad Data: " + line ); break; }` between splitting and accessing the Array. – Tim Hunter Jun 18 '21 at 14:30

2 Answers2

0

Check if your data is clean in the file (data.txt). It will not work if there is a single empty line or basically any line not in the desired format.

Example: a12387beac8 Apple 1 1500 /location/photo.jpeg

Vikas Adyar
  • 149
  • 1
  • 8
0

I hope you are trying to split based on white space. try this:

String[] pieces = line.split("\\s+");
Rawfodog
  • 13
  • 4