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 char
s 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?
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.