Rewriting into a file - java

I write a simple function like this:
private static void write(String Swrite) throws IOException {
if(!file.exists()) {
file.createNewFile();
}
FileOutputStream fop=new FileOutputStream(file);
if(Swrite!=null)
fop.write(Swrite.getBytes());
fop.flush();
fop.close();
}
Every time I call it, it rewrite and then I just get the last items that are written. How can I change it to not rewriting? The file variable is defined globally as a File.

On your FileOutputStream constructor, you need to add the boolean append parameter. It will then look like this:
FileOutputStream fop = new FileOutputStream(file, true);
This tells FileOutputStream that it should append the file instead of clearing and rewriting all of its current data.

Use constrctor which takes append flag as parameter.
FileOutputStream fop=new FileOutputStream(file, true);

you should open the file in append mode for this, by default FileOutputStream opens file in write mode. And you need not check for existence of file, it will be done implicitly by FileOutputStream
private static void write(String Swrite) throws IOException {
FileOutputStream fop=new FileOutputStream(file, true);
if(Swrite!=null)
fop.write(Swrite.getBytes());
fop.flush();
fop.close();
}

Try RandomAccessFile if your trying to write at certain byte offsets.

Tow parameter constructor is right. And it is redundant:
if(!file.exists()) {
file.createNewFile();
}
Constructor will do it for you.

Related

How to create and output to files in Java

My current problems lie with the fact that no matter what solution I attempt at creating a file in Java, the file never, ever is created or shows up.
I've searched StackOverflow for solutions and tried many, many different pieces of code all to no avail. I've tried using BufferedWriter, PrintWriter, FileWriter, wrapped in try and catch and thrown IOExceptions, and none of it seems to be working. For every field that requires a path, I've tried both the name of the file alone and the name of the file in a path. Nothing works.
//I've tried so much I don't know what to show. Here is what remains in my method:
FileWriter fw = new FileWriter("testFile.txt", false);
PrintWriter output = new PrintWriter(fw);
fw.write("Hello");
I don't get any errors thrown whenever I've run my past code, however, the files never actually show up. How can I fix this?
Thank you in advance!
There are several ways to do this:
Write with BufferedWriter:
public void writeWithBufferedWriter()
throws IOException {
String str = "Hello";
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write(str);
writer.close();
}
If you want to append to a file:
public void appendUsingBufferedWritter()
throws IOException {
String str = "World";
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
writer.append(' ');
writer.append(str);
writer.close();
}
Using PrintWriter:
public void usingPrintWriteru()
throws IOException {
FileWriter fileWriter = new FileWriter(fileName);
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print("Some String");
printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000);
printWriter.close();
}
Using FileOutputStream:
public void usingFileOutputStream()
throws IOException {
String str = "Hello";
FileOutputStream outputStream = new FileOutputStream(fileName);
byte[] strToBytes = str.getBytes();
outputStream.write(strToBytes);
outputStream.close();
}
Note:
If you try to write to a file that doesn’t exist, the file will be created first and no exception will be thrown.
It is very important to close the stream after using it, as it is not closed implicitly, to release any resources associated with it.
In output stream, the close() method calls flush() before releasing the resources which forces any buffered bytes to be written to the stream.
Source and More Examples: https://www.baeldung.com/java-write-to-file
Hope this helps. Good luck.
A couple of things worth trying:
1) In case you haven't (it's not in the code you've shown) make sure you close the file after you're done with it
2) Use a File instead of a String. This will let you double check where the file is being created
File file = new File("testFile.txt");
System.out.println("I am creating the file at '" + file.getAbsolutePath() + "');
FileWriter fw = new FileWriter(file, false);
fw.write("Hello");
fw.close();
As a bonus, Java's try-with-resource will automatically close the resource when it's done, you might want to try
File file = new File("testFile.txt");
System.out.println("I am creating the file at '" + file.getAbsolutePath() + "');
try (FileWriter fw = new FileWriter(file, false)) {
fw.write("Hello");
}

When opening an output file how does the filename get attached to the constructor if there's no field for it?

When you open an output file in Java, where does the name of the file get attached to the constructor if there is no field for it? Or does it just get attached to the file?
PrintWriter outputFile = new PrintWriter(fileName);
//Where does the filename go? I haven't had
//a good example of the outputfile's constructors in class
When passed a String (containing the intended file name) the PrintWriter constructor will internally create a FileOutputStream that is itself constructed using that file name.
It will then create an OutputStreamWriter that refers to the stream, retaining a (protected) reference to that writer, e.g. (in simplified form, without error checking):
protected Writer out;
public PrintWriter(String filename) {
OutputStream os = new FileOutputStream(filename);
out = new OutputStreamWriter(os);
}
All subsequent output is done via the out member variable, and the PrintWriter has no further use for the filename, hence why there's no member variable associated with it.
It's passed to the Outputstream you pass as a parameter for the Writer. Example:
try (final FileOutputStream fos = new FileOutputStream(new File("filename"))) {
final PrintWriter pw = new PrintWriter(fos);
}
The string you pass in the constructor is the full file' path, i.e. /data/my-file.txt.
If the file exists, you'll override its content. Otherwise, you'll create it and write inside it.
Here is another example:
FileWriter fstream;
try {
fstream = new FileWriter("1111.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write ("line 11111\r\n");
out.write("line 1222\r\n");
out.write("line 33\r\n");
out.close();
} catch (IOException e) {
// handle exception
e.printStackTrace();
}

How Can I Create A File In Java?

I am working on a program that needs a lot of app data. I am trying to create a function that creates a file with the path/file name of the string path. Here's my code:
public static void CreateFile(String path) throws FileNotFoundException, UnsupportedEncodingException {
PrintWriter writer = new PrintWriter(path, "UTF-8");
writer.close();
}
What did I do wrong? Shouldn't it create a file?
you can refer to this code :
FileWriter fw = new FileWriter("C:\\FileW3.txt");// you can give path here
//or
FileOutputStream fos = new FileOutputStream("path name");
PrintWriter pw = new PrintWriter (new OutputStreamWriter(fos));
pw.write("Combo stream and writer + using PrintWriter's write() methood/n");
pw.println();
pw.println("now using PrintWriter's println() methood");
pw.flush();
pw.close();
Also
File f = new File("path and filename");
This wont create a file , the file object can be used as parameter in FileWriter or FileOutputStream to create and then write to that file.
File object is just abstract representation of file.
It seems that you want to create an empty file. For this, you can use Files.createFile or File.createNewFile (but it will require you to instantiate a File).
To create a non-empty file, just write something in it and it will be automatically created if it does not exist.
Please see this link in the doucmentation - Create a file object then call 'createNewFile()' method on the newly created object.

Write text to the next line using Java

So i'm trying to write stuff to a file and it works but when i call this method more than once it removes the previous stuff i wrote with the new. So i wonder what should i do so the method wont remove my previous text that i've added to the file and adds the new text to the
next line.
public static void writetofile(String id, String content) throws IOException
{
try {
FileWriter filewriter = new FileWriter("Random.txt");
BufferedWriter out = new BufferedWriter(filewriter);
out.write(id+" "+ content);
out.close();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
FileWriter filewriter = new FileWriter("Random.txt", true);
As per java doc
Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
Parameters:
file - a File object to write to
append - if true, then bytes will be written to the end of the file rather than the beginning
There is constructor signature of FileWriter with a boolean parameter which controls append behavior. Providing that appending is what you want, you should construct the FileWriter with this boolean set to true:
FileWriter filewriter = new FileWriter("Random.txt", true);
Note, that in case of single parameter constructor the output is written to the beginning of the file (see the implementation of FileOutputStream which is wrapped by FileWriter), so calling single parameter constructor is equivalent to setting the boolean parameter to false.

How to append/write huge data file text in Java

I have a database with 150k records. I want to write this to file as fast as possible. I've tried many approaches, but all seem slow. How do I make this faster?
I read these records in blocks of 40k. So first I read 40k then another 40k and so on.
After reading the records, this process returns a StringBuilder which contains 40k lines. Then we write this StringBuilder to a file.
private static void write(StringBuilder sb, Boolean append) throws Exception {
File file = File.createTempFile("foo", ".txt");
FileWriter writer = new FileWriter(file.getAbsoluteFile(), append);
PrintWriter out = new PrintWriter(writer);
try {
out.print(sb);
out.flush();
writer.flush();
} finally {
writer.close();
out.close();
}
}
I read this other example but it is equally slow: Fastest way to write huge data in text file Java
I also tried it with NIO api:
private static void write(StringBuilder sb, Boolean append)) throws Exception {
FileChannel rwChannel = new FileOutputStream("textfile.txt", true).getChannel();
ByteBuffer bb = ByteBuffer.wrap(sb.toString().getBytes("UTF-8"));
rwChannel.write(bb);
rwChannel.close();
}
Which is the best method to write/append huge data into file?
You don’t need a PrintWriter here. If you have whatever kind of Writer (e.g. a FileWriter) you can simply invoke append(sb) on it. And you don’t need to flush, close implies flushing.
private static void write(StringBuilder sb, Boolean append) throws Exception {
File file = File.createTempFile("foo", ".txt");
try(FileWriter writer = new FileWriter(file.getAbsoluteFile(), append)) {
writer.append(sb);
}
}
On my system I encountered a small performance improvement using a Channel rather than an OutputStream:
private static void write0a(StringBuilder sb, Boolean append) throws Exception {
File file = File.createTempFile("foo", ".txt");
try(Writer writer = Channels.newWriter(new FileOutputStream(
file.getAbsoluteFile(), append).getChannel(), "UTF-8")) {
writer.append(sb);
}
}
However these are only slight improvements. I don’t see much possibilities here as all the code ends up calling the same routines. What could really improve your performance is keeping the Writer alive during the invocations and not flushing every record.
If you have a huge amount of data, it's better that you don't store it to StringBuilder and then write it to file at once.
This is the best scenario:
1) Before you start process on the data create FileInputStream
FileOutputStream fos = new FileOutputStream("/path/of/your/file");
2) Create and OutputStreamWriter from this file
OutputStreamWriter w = new OutputStreamWriter(fos, "UTF-8");
3) Create BufferedWriter (Improve file writing performance)
BufferedWriter bw = new BufferedWriter(w);
4) Pass bw to your process function and then flush/close
bw.flush();
bw.close();
The functionality of StringBuilder and BufferedWriter is almost same, So you do not need to change your code so much. The only negative point of this scenario is that, your process will involve all the time that the data are writing to file, but if you don't process the data in different thread, it is not an issue.
In this way, it doesn't matter how large data is it
You are using a FileWriter (or a FileOutputStream in the second example). These are not buffered! So they write single chars resp. bytes to the disk.
That means, you should wrap the FileWriter in a BufferedWriter (or the FileOutputSystem in a BufferedOutputSystem).
private static void write(StringBuilder sb, Boolean append) throws Exception {
File file = File.createTempFile("foo", ".txt");
Writer writer = new BufferedWriter(new FileWriter(file.getAbsoluteFile(), append));
PrintWriter out = new PrintWriter(writer);
try {
out.print(sb);
out.flush();
writer.flush();
} finally {
writer.close();
out.close();
}
}
You are opening the file, writing one line, then closing it. It's the opening and closing that takes the time here. Find a way to keep the output file open.
Did you try Apache IO, is the performance still the same?

Categories

Resources