We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Im wrote the following code but i wanna make it so that it will not overwrite the existing strings in the .txt file. Every time i run the sketch the createWriter command overwrites the .txt file. How do i make it so that it keeps the strings in the .txt file even when i run the sketch again?
Also i only want to print the first 10 lines of the txt file in the console when i press the ENTER key. But if the file contains only 3 lines i get an ArrayIndexOutOfBoundsException. How do i stop this from happening?
PrintWriter history;
void setup() {
size(700, 350);
history = createWriter("history.txt");
}
void draw() {
}
void keyPressed() {
if ((key=='1')) {
history.println("User pressed 1");
}
if ((key=='2')) {
history.println("User pressed 2");
}
if ((key == ENTER)) {
history.flush();
history.close();
String[] history = loadStrings("history.txt");
for (int i = 0; i <= 9; i++) { //only print first 10 lines
printArray("[" + i + "] " + history[i]);
}
}
}
Any help will be appreciated :)
Answers
Are you trying to append the data to the end of the file?
If so, Google "Java append to file" for a ton of results. But basically you need to create a
FileWriter
that's set to append and then use that to write your strings.use history.length instead of 9 in your for loop.