Reputation: 15
I have been trying to fix my for statement for some time now and I now have to bother you lot!
I am reading a .txt file, storing its data into an array called temp
. I am adding a new string to this array and then saving it back to the .txt file. Simple...I know!
My code is as follows:
public static void main(String[] args) throws IOException {
// Defining
String token = "";
// Tokensize user input.
Scanner action = new Scanner(System.in);
String tokenized = action.nextLine();
String[] tokenizes = tokenized.split("\\s");
// Read the 'greetings' part of the first sentence.
// Open 'greetings.txt' and save data to an array.
Scanner file1 = new Scanner(new File("greetings.txt"));
List<String> temp = new ArrayList<String>();
while (file1.hasNext()) {
token = file1.next();
temp.add(token);
}
temp.add(tokenized);
file1.close();
System.out.println(temp);
System.out.println(temp.get(1));
System.out.println(temp.get(2));
int arraylength = temp.size();
System.out.println(arraylength);
// Write the users greetings into the .txt.
// Overwrite old greetings array data.
PrintWriter writing = new PrintWriter("greetings.txt");
for (int i = 0; i < arraylength; i++) {
writing.println(temp.get(i));
writing.write("\n");
writing.close();
}
}
}
The issue is, the for loop only saves temp(0)
to the greetings.txt
file. It's not cycling through i
to arraylength
.
Upvotes: 0
Views: 53
Reputation: 11
Your closing writing in your for loop. Moving writing.close () after your for loop should do the trick.
Upvotes: 0
Reputation: 4845
Move writing.close();
out of the for loop. In the code you provided you close the print writer in the first iteration (you call writer.close()
in each iteration, in fact). That is, change
for (int i = 0; i < arraylength; i++) {
writing.println(temp.get(i));
writing.write("\n");
writing.close();
}
into
for (int i = 0; i < arraylength; i++) {
writing.println(temp.get(i));
writing.write("\n");
}
writing.close();
Upvotes: 2