So I am having troubles printing to output. I understand the concept, but when it comes to this problem its kinda weird. I\'ve tried different print lines and all of them give m
Try this:
PrintWriter output = new PrintWriter("test.txt");
output.println(data[0]); //this is where you call the println
for (int i = 0; i < data.length; i++) {
output.printf( ", %d", data[i]);
output.flush();
}
To make it a new line for each output loop it and add "\n" to each line you write or you can convert to string and edit String format to whatever you want. You can add a comma if you want
string.format()
Cause of problem: In your code, everytime you call text()
, you are replacing existing file, without updating or appending new data to it.
Refer this SO question. You can write printWriter as
PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("test.txt", true)));
I have tested on local, Try this code.
public void text() {
try {
// Adding data to existing file without replacing it.
PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("test.txt", true)));
output.print(data[0]);
for (int i = 1; i < data.length; i++) {
output.printf(", %d", data[i]);
}
output.print("\n"); // Added next line in the file
output.flush();
output.close(); // closing PrintWriter.
} catch (Exception ex) {
// log your exception.
}
}
Try this :
public void text() {
try {
PrintWriter output = new PrintWriter("test.txt");
output.println(data[0]);
for (int i = 0; i < data.length; i++) {
if (i != (data.length - 1)) {
output.printf("%d, ", data[i]);
} else {
output.printf("%d", data[i]);
}
output.flush();
}
} catch (Exception ex) {
}
}
try do in this way
public void text() {
try {
PrintWriter output = new PrintWriter("test.txt");
for (int i = 0; i < data.length; i++) {
if(i > 0){
output.print(",");
}
output.print(data[i]);
output.flush();
}
} catch (Exception ex) {
}
}