0

I've made an algorithm that alphabetically sorts a text file of names into an array, as it stands, the sorted array is around 21'000 names long. It outputs to the console fine (I used a delayed output due to the fact that the console cuts out after a while), but when I try to output to a file it stops 2 thirds into the array, around the letter "T".

Any suggestions? Here is my output code:

    BufferedWriter bw = new BufferedWriter(new FileWriter("E:\\output.txt"));

    for (int i = 0; i < names.length; i++){
        System.out.println(names[i]);
        bw.write(names[i]);
        bw.newLine();}

I have also tried to output starting from the end of the array

for (int i = names.length-1; i >= 0; i--){
        System.out.println(names[i]);
        bw.write(names[i]);
        bw.newLine();}

In this case the array stops outputting to the file around the letter "B". I thought maybe there was an overflow or something outputting to the file, but even adding a delay to each loop still yielded the same result.

1 Answers1

0

Use a "try with resources" to guarantee that your writer will be closed. Or if you do not want to close it at the moment, call the "flush" method.

try (BufferedWriter bw = new BufferedWriter(new FileWriter("E:\\output.txt"))) {

    for (int i = 0; i < names.length; i++){
        System.out.println(names[i]);
        bw.write(names[i]);
        bw.newLine();
    }
}
Boschi
  • 622
  • 3
  • 10