Mar Oli Mar Oli - 2 months ago 10
Java Question

Why my method don't read all of my File? ... Java?

I have to display all of records in my blocks (text files), and do a split to "cover" the Fields Separators, but only the first record of my blocks are diplayed. What am I doing wrong?

enter code here
public static void listAllStudents() throws IOException {

File path = new File(Descriptor.getBlockPath());

for (int i = 0; i < path.listFiles().length; i++) {

try {
FileInputStream file = new FileInputStream(Descriptor.getBlockPath() + "BLK" + i + ".txt");
InputStreamReader entrada = new InputStreamReader(file);
BufferedReader buf= new BufferedReader(entrada);
String piece = " ";

System.out.println("\nBLOCO " + i + " ------------------------------------------------------ +");

do {


if (buf.ready()) {
piece = buf.readLine();
System.out.println("\n¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨");

String string = " ", field[] = piece.split(Descriptor.getFieldSeparator());
string = " ";

System.out.println("CPF: " + field[0]);
System.out.println("Name: " + field[1]);
System.out.println("Course: " + field[2]);
System.out.println("Age: " + field[3]);
System.out.println("Phone: " + field[4]);
System.out.println("Active: " + field[5]);

string = " ";
}

} while (buf.ready());

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

}

Answer

See the documentation for the BufferedReader.readLine() method:

or null if the end of the stream has been reached

Then change your code to read the file line by line:

while ((piece = buf.readLine()) != null) {
     String field[] = piece.split(Descriptor.getFieldSeparator());

     if (field.length >= 6) {
                System.out.println("CPF: " + field[0]);
                System.out.println("Name: " + field[1]);
                System.out.println("Course: " + field[2]);
                System.out.println("Age: " + field[3]);
                System.out.println("Phone: " + field[4]);
                System.out.println("Active: " + field[5]);
     }
}