Kai Adam Kai Adam - 5 months ago 15
Java Question

Java - Won't read out File content

I have a .txt file with, for example, this content:

variable1="hello";
variable2="bye";
testing3="parameter";
whatisthis4="hello";
var5="exampletext";
example=3;
wellthen=8;
---


It read in the file, line by line, fine until I added a way of saving the data.

This whole code plus another reader (with other variable names of course) is wrapped in a try-catch statement.

String path_playlist = new File("").getAbsolutePath();
String fileName_playlist = path_playlist
+ "/src/dancefusion/game/playlist.txt";
FileReader fr_playlist = new FileReader(fileName_playlist);
BufferedReader br_playlist = new BufferedReader(fr_playlist);

int track_counter = track_sum*9;
String trackinfos[] = new String[track_counter];

while(track_counter < 0)
{
System.out.println("linecount="+track_counter);
trackinfos[track_counter] = br_playlist.readLine();
System.out.println(trackinfos[track_counter]);
track_counter--;
}
System.out.println(Arrays.toString(trackinfos));


In this example track_sum equals 1.

The while loop should read in the file one line at a time but only reads null's:

[null, null, null, null, null, null, null, null, null]





Update 1:

The while-condition was set up the wrong way... thanks!

The corrected version:

while(track_counter < 0)


However, now it gives me an exception with an "ArrayOutOfBounds: 9".

Any guesses?




Final Update:

As mentioned by @GiorgiMoniava, I just needed to reduce track_counter by one before starting to read in as in Java arrays begin with 0, thanks!

int track_counter = track_sum*8;
String trackinfos[] = new String[track_counter];

track_counter--;

while(track_counter >= 0)
{
System.out.println("linecount="+track_counter);
trackinfos[track_counter] = br_playlist.readLine();
System.out.println(trackinfos[track_counter]);
track_counter--;
}





Maybe one of you can figure out what I did wrong...

Of course I can deliver more information/code if needed!
Thanks in advance!

Answer

This looks weird

while(track_counter < 0)

Are you sure loop is ever entered in? It is my guess (from your output) that track_counter is 9.

About your array out of bounds exception: if you create array of size N you can only access it using indexes: [0, N-1]