For-loop not executing File writing commands

50 views Asked by At

I have a program that is supposed to generate a file with a random integer name and append 200 characters of data to each file. I have already succeeded in being able to create a file:

BufferedOutputStream bos = new BufferedOutputStream(Files.newOutputStream(
         new File("C:/Users/mirvine/Desktop/SPAM").toPath()));

And I have gotten it to write chars to the file:

bos.write((char)rand.nextInt(255));

But when I combine the two with a for loop, it doesn't work:

try {
            while(true) {
                int i = rand.nextInt();
                File outputFile = new File("C:/Users/mirvine/Desktop/SPAM/"+ String.valueOf(i) +".txt");

                    bos = new BufferedOutputStream(Files.newOutputStream(outputFile.toPath()));
                    PrintWriter writer = new PrintWriter(bos);
                    for(int qu = 0; qu <= 2000; qu++) {
                        writer.write((char)rand.nextInt(255));
                        System.out.println("Total " + String.valueOf(qu) + " characters written to " + String.valueOf(i) + ".txt!");
                }
                    System.out.println("File named \'" + String.valueOf(i) + ".txt\' created!");

            }
        } catch (Exception e) {e.printStackTrace(); return;}

I will get the output "Total: (number) characters written to (whatever).txt!" but it won't actually write the characters. However, if I make the loop infinite (by changing qu++ to qu--) it will write the characters, of course with only one file though. I even tried changing it to a while loop and it didn't work. Any ideas?

2

There are 2 answers

1
Fallso On BEST ANSWER

Consider changing the use of BufferedOutputStream and PrintWriter for FileWriter, which will take your file as an argument to the constructor.

Also, make sure you flush and close the stream after finishing with it.

1
ToYonos On

You should use a BufferedWriter, it's more efficient, and don't forget to close it at the end. The infinite loop is useless.

int i = rand.nextInt();
File outputFile = new File("C:/Users/mirvine/Desktop/SPAM/"+ String.valueOf(i) +".txt");
FileOutputStream fos = new FileOutputStream(outputFile);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));  
for(int qu = 0; qu <= 2000; qu++)
{
    bw.write((char)rand.nextInt(255));
    System.out.println("Total " + String.valueOf(qu) + " characters written to " + String.valueOf(i) + ".txt!");
}
bw.close();