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();
}