I have a simple application that yet would trash a text file (it\'s just practice) I\'m only 3 days with Java yet. Problem is there are no errors until you run the program then
FileWriter file = new FileWriter("hello.txt");
String sb = " ";
for (int i = 0; i < 1; i++) {
sb += alphabet.charAt(r.nextInt(N));
System.out.println(sb);
int length = sb.length();
file.write(sb);
file.close();
if(length == 30){
sb = " ";
}
}
You are initializing FileWriter once and closing it in the 1st iteration itself then trying to use it again in next iteration. Hence you are getting an Exception.
I recommend put your for loop in try statement and close your FileWriter in finally statement. Here is oracle tut on try-catch-finally construct.
Final code will go something like below
FileWriter file = null;
try {
try {
file = new FileWriter("hello.txt");
String sb = " ";
for (int i = 0; i < 1; i++) {
sb += alphabet.charAt(r.nextInt(N));
System.out.println(sb);
int length = sb.length();
file.write(sb);
if (length == 30) {
sb = " ";
}
}
} finally {
file.close();
}
} catch (IOException e) {
e.printStackTrace();
}
Your should close the FileWriter outside the for loop.
file.close();
Another problem with your code is that no increment is done on i in the loop. Thus it is a infinite loop and you program won't stop(after resolving the exception). Try something like:
for (int i = 0; i < 1; i++)
or add a break condition within the body.
Actual writing while being in a loop will not take place unless you call file.flush() method.
FileWriter fileWriter = new FileWriter("hello.txt");
try {
for (int i = 0; i < 10; i++) {
fileWriter.write(line);
fileWriter.flush();
}
} finally {
fileWriter.close();
}
Only close your FileWriter stream once you are completely done using it.
Also, the write method for FileWriter does not include a method for only a String parameter. That might be the garbage you are getting when reading the file.
The problem is that you are closing your FileWriter
and trying to use it again.
Instead, close the writer after you've finished the loop:
try (FileWriter file = new FileWriter("hello.txt")) {
String sb = " ";
for (int i = 0; i < 1; i++) { // Note: added a i++
sb += alphabet.charAt(r.nextInt(N));
System.out.println(sb);
int length = sb.length();
file.write(sb);
// file.close(); <---- NOPE: don't do this
if (length == 30) {
sb = " ";
}
}
}
Thanks to Andrew for spotting the i++
omission.
When you close the file as in the following line
file.close()
it means you are done working with the file.
In your case you close the file in the loop which means the next iteration will throw an exception.
Move the above mentioned code out of the loop.