Java: Append A String On A New Line In The Target File

Java

###TODAY’S TIPS###
Setting append flag to True enables output stream to be appended, not overwritten.

fileOutputStream = new FileOutputStream(textFile, true)

String could be appended on a new line through one additional step like the code below.

str = System.lineSeparator() + str;

###
If the append flag is not set to true, the destination file is overwritten, the current data would be lost.

If you want to append string on a new line, just setting flag true is not enough to achieve it.
The string would append just behind the last character of the destination text file unless a bit of modification is done to the string to append.

To add a new line separator to the string, it is said that “System.lineSeparator()” should be used, not hard coding like “\n”, because of the new line separator’s diversity among systems the code will run on.

###SAMPLE CODE###

package input_test;
import java.io.*;
import java.util.Scanner;

public class Inputstream_test {

public static void main(String[] args) {

System.out.print(“type any sentence: “);

Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
scan.close();
str = System.lineSeparator() + str;
byte[] dataBytes = str.getBytes();
File textFile = new File(“new_textfile.txt”);
OutputStream fileOutputStream = null;
 
try {

fileOutputStream = new FileOutputStream(textFile, true);
fileOutputStream.write(dataBytes);

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (fileOutputStream != null) {

fileOutputStream.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

タイトルとURLをコピーしました