I have coded the following FileWriter
:
try { FileWriter writer = new FileWriter(new File("file.txt"), false); String sizeX = jTextField1.getText(); String sizeY = jTextField2.getText(); writer.write(sizeX); writer.write(sizeY); writer.flush(); writer.close(); } catch (IOException ex) {}
Now I want to insert a new line, just like you would do it with \n
normally, but it doesn't seem to work.
What can be done to solve this?
Thank you.
write("\r\n"); or better writer.
In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.
FileWriter(File file) : Creates a FileWriter object using specified File object. It throws an IOException if the file exists but is a directory rather than a regular file or does not exist but cannot be created, or cannot be opened for any other reason.
In order to create a file writer, we must import the Java.io.FileWriter package first. Once we import the package, here is how we can create the file writer. 1. Using the name of the file. FileWriter output = new FileWriter (String name); Here, we have created a file writer that will be linked to the file specified by the name.
FileWriter (File file): Constructs a FileWriter object given a File object. It throws an IOException if the file exists but is a directory rather than a regular file or does not exist but cannot be created, or cannot be opened for any other reason. FileWriter fw = new FileWriter (File file); 2.
FileWriter.write (" "); add the newline to your file. Better use newLine () of the BufferedWriter class. You're overwriting the file contents due to the use of new FileWriter (fileName); (read the JavaDoc on that class/constructor). Use new FileWriter (fileName, true); to append to the file instead.
To create FileWriter, use one of its constructors. All constructors will need at least the file name or File object referring to the file where we want to write the text. Setting the Charset information is optional. If not provided, system’s default charset will be used.
If you want to get new line characters used in current OS like \r\n
for Windows, you can get them by
System.getProperty("line.separator");
System.lineSeparator()
String.format("%n");
You can also use PrintStream
and its println
method which will add OS dependent line separator at the end of your string automatically
PrintStream fileStream = new PrintStream(new File("file.txt")); fileStream.println("your data"); // ^^^^^^^ will add OS line separator after data
(BTW System.out
is also instance of PrintStream).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With