[java] write newline into a file

considering the following function

private static void GetText(String nodeValue) throws IOException {

   if(!file3.exists()) {
       file3.createNewFile();
   }

   FileOutputStream fop=new FileOutputStream(file3,true);
   if(nodeValue!=null)
       fop.write(nodeValue.getBytes());

   fop.flush();
   fop.close();

}

what to add to make it to write each time in the next line?

for example i want each words of a given string in a seperate lline for example:

i am mostafa

writes as:

 i
 am
 mostafa

This question is related to java file newline

The answer is


Solution:

in WINDOWS you should write "\r\n" for a new line.


Or you could use something like the following. Pay attention to "\n":

/**
 * Created by mona on 3/26/16.
 */
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
public class FileExample {


    public static void main (String[] args) throws java.io.IOException {

        File newFile = new File("tweet.txt");
        FileWriter fileWriter = new FileWriter(newFile);
        fileWriter.write("Mona Jalal");
        fileWriter.append("\nMona Mona");
        fileWriter.close();
        FileReader fileReader = new FileReader(newFile);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
        fileReader.close();
        bufferedReader.close();



    }
}

Files.write(Paths.get(filepath),texttobewrittentofile,StandardOpenOption.APPEND ,StandardOpenOption.CREATE);    

This creates a file, if it does not exist If files exists, it is uses the existing file and text is appended If you want everyline to be written to the next line add lineSepartor for newline into file.

String texttobewrittentofile = text + System.lineSeparator();

You could print through a PrintStream.

PrintStream ps = new PrintStream(fop);
ps.println(nodeValue);
ps.close();

the other answers should work. however I wanna mention

from java doc:

FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream.

reading your method codes, you are about to write String to the file, what you were doing is convert String to raw bytes, then write so I think using FileWriter is not a bad idea.

And for the newline problem, Writer has method .write(String), which is convenient to use.


just use \r\n for endline if you are using windows operating system.


if(!file3.exists()){
    file3.createNewFile();
}
FileOutputStream fop=new FileOutputStream(file3,true);
if(nodeValue!=null) fop.write(nodeValue.getBytes());

fop.write("\n".getBytes());

fop.flush();
fop.close();

You need to add a newline at the end of each write.


Change the lines

if(nodeValue!=null)
    fop.write(nodeValue.getBytes());

fop.flush();

to

if(nodeValue!=null) {
    fop.write(nodeValue.getBytes());
    fop.write(System.getProperty("line.separator").getBytes());
}

fop.flush();

Update to address your edit:

In order to write each word on a different line, you need to split up your input string and then write each word separately.

private static void GetText(String nodeValue) throws IOException {

    if(!file3.exists()) {
        file3.createNewFile();
    }

    FileOutputStream fop=new FileOutputStream(file3,true);
    if(nodeValue!=null)
        for(final String s : nodeValue.split(" ")){
            fop.write(s.getBytes());
            fop.write(System.getProperty("line.separator").getBytes());
        }
    }

    fop.flush();
    fop.close();

}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?

Examples related to newline

How can I insert a line break into a <Text> component in React Native? Print "\n" or newline characters as part of the output on terminal Using tr to replace newline with space How to write one new line in Bitbucket markdown? Line break in SSRS expression How to insert a new line in Linux shell script? Replace CRLF using powershell How to write new line character to a file in Java What is the newline character in the C language: \r or \n? How to print values separated by spaces instead of new lines in Python 2.7