I have the above code. What i wanna do is to write in a txt file a string.
import java.io.*;
import java.util.*;
public void writeAsfalizomenos(asfalizomenos myObj) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.print("Surname: ");
String username = scanner.nextLine();
System.out.println(username);
FileWriter outFile = new FileWriter("asdf.txt", true);
PrintWriter out1 = new PrintWriter(outFile);
out1.append(username);
out1.println();
out1.append("adfdas");
//
// Read string input for username
//
}
public static void main(String [] args) throws IOException{
asfalizomenos a = new asfalizomenos();
a.writeAsfalizomenos(a);
}
The above code creates a txt file but it doesnt write the string to it. Any idea about my bug??
You’re not closing or flushing the
PrinterWriteror theFileWriter. So basically it’s being buffered, so nothing is being written to the file.You should close both in finally blocks:
Closing will flush automatically.
(I can’t remember – it’s likely that closing the
PrintWriterwill close theFileWriter. Personally I like to be explicit about it anyway.)