Writing Multiple Lines to a File (.txt) in Java [duplicate] - java

This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 4 years ago.
I am new to File Streams and would appreciate some help. The following code is the code I use to write to a specified file.
OutputStream outStream = new FileOutputStream(file);
outStream.write(contentsToWrite.getBytes());
outStream.close();
How do I save different lines to a file? In my case using \n does not work when writing to a file.
How do I save a line to the file without deleting the other lines?

There is a nice, simple method which allows you to do this with a List of Strings you want to write and the file itself.
List<String> lines=new ArrayList<>(contentToWrite);//if it is an array or something that isn't a list
Files.write(file.toPath(),lines);

Java has some wrapper class to file streams. BufferedWriter can be used to write string to file.
boolean append = true;
String filename = "/path/to/file";
BufferedWriter writer = new BufferedWriter(new FileWriter(filename, append));
// OR: BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename, append)));
writer.write(line1);
writer.newLine();
writer.write(line2);
writer.newLine();
// ......
writer.close();
append meanings you write to the end of the file instead of empty the file.

The FileOutputStream class constructor method has the second parameter. if you set it to true. It will append the content the file you write. And "\r\n" can change to a new line.
OutputStream outStream = new FileOutputStream("a.txt",true);
outStream.write("hello".getBytes());
outStream.write("\r\n".getBytes());
outStream.write("hello".getBytes());
outStream.close();

Related

Java - how to replace file contents? [duplicate]

This question already has answers here:
Is this the best way to rewrite the content of a file in Java?
(8 answers)
Closed 6 years ago.
I have a file that contains only a very small amount of information that needs to be updated periodically. In other words, I want to truncate the file before writing to it. The easiest solution I found was to delete and create it again as shown here:
File myFile = new File("path/to/myFile.txt");
myFile.delete();
myFile.createNewFile();
// write new contents
This 'works' fine, but is there a better way?
There is no need to delete the file and recreate one. If you are writing to the file, for instance using PrintWriter, it will overwrite your current file content.
Example:
public static void main(String[] args) throws IOException
{
PrintWriter prw= new PrintWriter (“MyFile.txt”);
prw.println("These text will replace all your file content");
prw.close();
}
It will only append to the end of the file if you use the overloaded version of the PrintWriter constructor:
PrintWriter prw= new PrintWriter (new FileOutputStream(new File("MyFile.txt"), true));
//true: set append mode to true
In the below example, the "false" causes the file to be overwritten, true would cause the opposite.
File file=new File("C:\Path\to\file.txt");
DataOutputStream outstream= new DataOutputStream(new FileOutputStream(file,false));
String body = "new content";
outstream.write(body.getBytes());
outstream.close();

Making a new line in a file [duplicate]

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 8 years ago.
Im trying to write a text to file, but it overwrites whats inside, can somebody explain how to check if the text exists and then put a new line and write? Here is the code I am working with:
try
{
if (!file.exists())
{
file.createNewFile();
}
FileWriter fw =
new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.newLine();
bw.write(petName);
bw.close();
System.out.println("Done!");
}
catch (IOException exc)
{
System.out.println(exc);
}
Thank you for any kind of help.
how to check if the text exists and then put a new line and write?
Use File#length() to check if the text exists in the file.
if(file.length()>0){
bw.newLine();
}
Note:
Open the file in append mode if you don't want to override the existing content of the file.
Use following to append if file exists.
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);

Appending Byte[] to end of a binary file

I'm parsing a file. I'm creating a new output file and will have to add the 'byte[] data' to it. From there I will need to append many many other 'byte[] data's to the end of the file. I'm thinking I'll get the user to add a command line parameter for the output file name as I already have them providing the file name which we are parsing. That being said if the file name is not yet created in the system I feel I should generate one.
Now, I have no idea how to do this. My program is currently using DataInputStream to get and parse the file. Can I use DataOutputStream to append? If so I'm wondering how I would append to the file and not overwrite.
If so I'm wondering how I would append to the file and not overwrite.
That's easy - and you don't even need DataOutputStream. Just FileOutputStream is fine, using the constructor with an append parameter:
FileOutputStream output = new FileOutputStream("filename", true);
try {
output.write(data);
} finally {
output.close();
}
Or using Java 7's try-with-resources:
try (FileOutputStream output = new FileOutputStream("filename", true)) {
output.write(data);
}
If you do need DataOutputStream for some reason, you can just wrap a FileOutputStream opened in the same way.
Files.write(new Path('/path/to/file'), byteArray, StandardOpenOption.APPEND);
This is for byte append. Don't forget about Exception
File file =new File("your-file");
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(your-string);
bufferWritter.close();
Of coruse put this in try - catch block.

Outputting a String into a file, without clearing the file

I've been working on sort of "logging" to text file using BufferedWriter and I came across a problem:
I run the following code.. fairly basic..
BufferedWriter out = new BufferedWriter(new FileWriter(path+fileName));
String str = "blabla";
out.write(str);
out.close();
and the next thing I know is that the entire file that had couple of lines of text has been cleared and only 'blabla' is there.
What class should I use to make it add a new line, with the text 'blabla', without having to get the entire file text to a string and adding it to 'str' before 'blabla'?
What class should I use to make it add a new line, with the text 'blabla', without having to get the entire file text to a string and adding it to 'str' before 'blabla'?
You're using the right classes (well, maybe - see below) - you just didn't check the construction options. You want the FileWriter(String, boolean) constructor overload, where the second parameter determines whether or not to append to the existing file.
However:
I'd recommend against FileWriter in general anyway, as you can't specify the encoding. Annoying as it is, it's better to use FileOutputStream and wrap it in an OutputStreamWriter with the right encoding.
Rather than using path + fileName to combine a directory and a filename, use File:
new File(path, fileName);
That lets the core libraries deal with different directory separators etc.
Make sure you close your output using a finally block (so that you clean up even if an exception is thrown), or a "try-with-resources" block if you're using Java 7.
So putting it all together, I'd use:
String encoding = "UTF-8"; // Or use a Charset
File file = new File(path, fileName);
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file, true), encoding));
try {
out.write(...);
} finally {
out.close()'
}
Try using FileWriter(filename, append) where append is true.
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
out.println("the text");
out.close();
} catch (IOException e) {
//oh noes!
}
The above should work: Source Reference

How to skip a number of lines when writing to a txt file

I'm making a program that will output lines to a text file. I don't wish to overwrite the file, but that is what my current code does. I just want to go down the number of lines that are already there and write hello. Here is my code:
FileWriter fileWriter = new FileWriter(fileLocation, false);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
while(numberOfLines > compareToNumOfLines) {
bufferedWriter.newLine();
compareToNumOfLines++;
}
bufferedWriter.write("hello");
bufferedWriter.close();
Unfortunately, this just creates spaces where the text used to be. What am I doing wrong?
Change
FileWriter fileWriter = new FileWriter(fileLocation, false);
to
FileWriter fileWriter = new FileWriter(fileLocation, true);
As explained in the documentation, the second argument is a boolean that specify if you want to append the text or overwrite it.
If you want to append text to existing file then open the file in append mode. If you want to write at random place in file then you can use RandomAccessFile class.

Categories