Writing to A Text File-Writing To Next Line - java

I'm appending to a text file but it won't go write to the next line, it keeps writing on the same line. I've tried .println() and PrintWriter.write("\r\n"); I'm not sure what else to do. (Windows System) Any help would be appreciated,
PrintWriter fOut;
try
{
fOut = new PrintWriter(new FileWriter("file_name.txt",true));
fOut.append("text\n");
fOut.close();
}
catch (IOException ex) {
Logger.getLogger(ScorePredictorFrame.class.getName()).log(Level.SEVERE, null, ex);
}

Assuming that file_name.txt already exists, and you want to write to the next line, I would do:
fOut.append("\r\ntext");

What is "text" in fOut.append("text\n");
if you are doing something like String text = ""; then you need to do it as fOut.append(text + "\n"); Else what you are doing is correct.

try
{
fOut = new PrintWriter(new FileWriter("file_name.txt",true));
fOut.println("text");
fOut.close();
}
The above code should work because according to the Java doc of the method it does enter the line separator
Terminates the current line by writing the line separator string. The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ('\n').
You can check the line.separator property using the following
final String lineSeparator = System.getProperty ( "line.separator" );

Related

File Writer - All going on one Line [duplicate]

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.
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");
since Java7 System.lineSeparator()
or as mentioned by Stewart generate them via 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).
Try System.getProperty( "line.separator" )
writer.write(System.getProperty( "line.separator" ));
Try wrapping your FileWriter in a BufferedWriter:
BufferedWriter bw = new BufferedWriter(writer);
bw.newLine();
Javadocs for BufferedWriter here.
Since 1.8, I thought this might be an additional solution worth adding to the responses:
Path java.nio.file.Files.write(Path path, Iterable lines, OpenOption... options) throws IOException
StringBuilder sb = new StringBuilder();
sb.append(jTextField1.getText());
sb.append(jTextField2.getText());
sb.append(System.lineSeparator());
Files.write(Paths.get("file.txt"), sb.toString().getBytes());
If appending to the same file, perhaps use an Append flag with Files.write()
Files.write(Paths.get("file.txt"), sb.toString().getBytes(), StandardOpenOption.APPEND);
Try:
String.format("%n");
See this question for more details.
If you mean use the same code but add a new line so that when you add something to the file it will be on a new line. You can simply use BufferedWriter's newLine().
Here I have Improved you code also: NumberFormatException was unnecessary as nothing was being cast to a number data type, saving variables to use once also was.
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"));
writer.write(jTextField1.getText());
writer.write(jTextField2.getText());
writer.newLine();
writer.flush();
writer.close();
} catch (IOException ex) {
System.out.println("File could not be created");
}
Here "\n" is also working fine. But the problem here lies in the text editor(probably notepad). Try to see the output with Wordpad.
One can use PrintWriter to wrap the FileWriter, as it has many additional useful methods.
try(PrintWriter pw = new PrintWriter(new FileWriter(new File("file.txt"), false))){
pw.println();//new line
pw.print("text");//print without new line
pw.println(10);//print with new line
pw.printf("%2.f", 0.567);//print double to 2 decimal places (without new line)
}
I would tackle the problem like this:
BufferedWriter output;
output = new BufferedWriter(new FileWriter("file.txt", true));
String sizeX = jTextField1.getText();
String sizeY = jTextField2.getText();
output.append(sizeX);
output.append(sizeY);
output.newLine();
output.close();
The true in the FileWriter constructor allows to append.
The method newLine() is provided by BufferedWriter
Could be ok as solution?
using simple \n to break line in write file and normal output in java

How to add a new line after writing a array of characters into a file using JAVA

After executing the following piece of code
String content = new String("CONSOLIDATED_UNPAID_code_" + code2 + "_" + countryCode2 + " = " + reason2);
try {
fileOutputStream.write(content.getBytes());
}
catch (IOException e) {
e.printStackTrace();
}
output is as follows:.
CONSOLIDATED_UNPAID_code_64 _KE = Account Dormant-Refer to DrawerCONSOLIDATED_UNPAID_code_65 _KE = Wrong/Missing Account Number (EFT)CONSOLIDATED_UNPAID_code_66 _KE = Wrong/Missing Reference
but i want it like
CONSOLIDATED_UNPAID_code_64 _KE = Account Dormant-Refer to Drawer
CONSOLIDATED_UNPAID_code_65 _KE = Wrong/Missing Account Number (EFT)
Pls suggest
I'd have to see the rest of the code to tell you exactly what you should do, but you can simply use the character "\n" in your string.
You can achieve adding new line to a file in quite a few ways, here is the two approaches:
Add a \n to your String which would cause the remainder of the string to be printed in new line
Use PrintWriter's println method to print each string in new line
Also keep in mind that opening a file with Notepad might not recognize \n hence do not display the remainder of string in new line, try opening the file using Notepadd++
String code2 = "code12";
String countryCode2 = "countryCode2";
String reason2 = " \n I am reason.";
String content = new String("CONSOLIDATED_UNPAID_code_" + code2 + "_" + countryCode2 + " = " + reason2);
try {
fout.write(content.getBytes());
//don't forget to flush the output stream
fout.flush();
} catch (IOException e) {
e.printStackTrace();
}
Use PrintWriter as shown below:
String line1 = "This is line 1.";
String line2 = "This is line 2.";
File f = new File("C:\\test_stackoverflow\\test2.txt");
PrintWriter out = new PrintWriter(f);
out.println(line1);
out.println(line2);
//close the output stream
out.close();
First, use a Writer on top of the output stream to write strings to files. This way, you'll be in control of the output character encoding.
Second, if you want to use your platform's line separator, you may use PrintWriter which has println() methods using the correct newline character or character sequence.
PrintWriter writer = new PrintWriter(
new OutputStreamWriter(fileOutputStream, OUTPUT_ENCODING)
);
...
writer.println(content);
Found solution for this . Appending /n wouldnt solve any issue rather use BufferedWriter. BufferedWriter has a inbuilt newline mwthod to do the same. Thanks
Solution:
try {
File file = new File("Danny.txt");
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fileOutputStream) );
String content = new String("CONSOLIDATED_UNPAID_description_"+code2+"_"+countryCode2+" = "+description2);
bw.write(content);
bw.newLine();
bw.flush();
check = true;
}
catch (IOException e) {
e.printStackTrace();
}

Remove a line in text file with java.BufferedReader

How can I remove or trim a line in a text file in Java?
This is my program but it does not work.
I want to remove a line in text file, a line contain the word of user input
try {
File inputFile = new File("temp.txt");
File tempFile = new File("temp1.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = name;
String currentLine;
while((currentLine = reader.readLine()) != null)
{
//trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(!trimmedLine.startsWith(lineToRemove))
{
// if current line not start with lineToRemove then write to file
writer.write(currentLine);
}
}
writer.close();
reader.close();
}
catch(IOException ex)
{
System.out.println("Error reading to file '" + fileName + "'");
}
You are not separating the lines with a line break character, so the resulting file will have one single long line. One possible way to fix that is just writing the line separator after each line.
Another possible problem is that you are only checking if the current line starts with the given string. If you want to check if the line contains the string you should use the contains method.
A third problem is that you are not writing the trimmed line, but the line as it is. You really don't say what you expect from the program, but if you are supposed to output trimmed lines it should look like this:
if(!trimmedLine.contains(lineToRemove)) {
writer.write(trimmedLine);
writer.newLine();
}
startsWith() is the culprit. You are checking if the line starts with "lineToRemove". As #Joni suggested use contains.

Create a new line in Java's FileWriter

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.
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");
since Java7 System.lineSeparator()
or as mentioned by Stewart generate them via 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).
Try System.getProperty( "line.separator" )
writer.write(System.getProperty( "line.separator" ));
Try wrapping your FileWriter in a BufferedWriter:
BufferedWriter bw = new BufferedWriter(writer);
bw.newLine();
Javadocs for BufferedWriter here.
Since 1.8, I thought this might be an additional solution worth adding to the responses:
Path java.nio.file.Files.write(Path path, Iterable lines, OpenOption... options) throws IOException
StringBuilder sb = new StringBuilder();
sb.append(jTextField1.getText());
sb.append(jTextField2.getText());
sb.append(System.lineSeparator());
Files.write(Paths.get("file.txt"), sb.toString().getBytes());
If appending to the same file, perhaps use an Append flag with Files.write()
Files.write(Paths.get("file.txt"), sb.toString().getBytes(), StandardOpenOption.APPEND);
Try:
String.format("%n");
See this question for more details.
If you mean use the same code but add a new line so that when you add something to the file it will be on a new line. You can simply use BufferedWriter's newLine().
Here I have Improved you code also: NumberFormatException was unnecessary as nothing was being cast to a number data type, saving variables to use once also was.
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"));
writer.write(jTextField1.getText());
writer.write(jTextField2.getText());
writer.newLine();
writer.flush();
writer.close();
} catch (IOException ex) {
System.out.println("File could not be created");
}
Here "\n" is also working fine. But the problem here lies in the text editor(probably notepad). Try to see the output with Wordpad.
One can use PrintWriter to wrap the FileWriter, as it has many additional useful methods.
try(PrintWriter pw = new PrintWriter(new FileWriter(new File("file.txt"), false))){
pw.println();//new line
pw.print("text");//print without new line
pw.println(10);//print with new line
pw.printf("%2.f", 0.567);//print double to 2 decimal places (without new line)
}
I would tackle the problem like this:
BufferedWriter output;
output = new BufferedWriter(new FileWriter("file.txt", true));
String sizeX = jTextField1.getText();
String sizeY = jTextField2.getText();
output.append(sizeX);
output.append(sizeY);
output.newLine();
output.close();
The true in the FileWriter constructor allows to append.
The method newLine() is provided by BufferedWriter
Could be ok as solution?
using simple \n to break line in write file and normal output in java

Strings are not written to a new line

Following snippet attempts to write the name of directories and files present in some directory to a text file.Each name should be written to a separate line.Instead it prints each name on the same line. Why is it so ?
try {
File listFile = new File("E:" + System.getProperty("file.separator") + "Shiv Kumar Sharma Torrent"+ System.getProperty("file.separator") +"list.txt");
FileWriter writer = new FileWriter(listFile,true);
Iterator iterator = directoryList.iterator();
while(iterator.hasNext()) {
writer.write((String)iterator.next());
writer.write("\n"); // Did this so each name is on a new line
}
writer.close();
}catch(Exception exc) {
exc.printStackTrace();
}
output:
Where am i making a mistake ?
Whenver you need textual formatting always use PrintWriter.
The right way of doing is to wrap the writer inside a PrintWriter and use println() method, like:
PrintWriter printWriter = new PrintWriter(writer);
printWriter.println();
If you are using Windows, use \r\n instead of \n.
or for OS-independent, use:
System.getProperty("line.separator");
You should write your next line as "\r\n" if you are on a Windows platform.
The next line for Windows is "\r\n"
The next line for Mac is "\n"
Alternatively, use System.getProperty("line.separator") for your line break. It automatically determines the right line break for the system it is running on. This should be the best practice since Java is expected to perform the same on different OS-es.
If you are going to use BufferedWriter :
File f = new File("C:/file.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
bw.write("Hello");
bw.newLine(); // new line
bw.write("How are you?");
bw.close();

Categories