I have below code
try
{
FileWriter fileWriter = new FileWriter("C:\\temp\\test.txt");
fileWriter.write("Hi this is sasi This test writing");
fileWriter.append("test");
}
catch(IOException ioException)
{
ioException.printStackTrace();
}
After executing it, the file is created successfully, but the created file is empty.
What is wrong with the code?
You must close the FileWriter, otherwise it won't flush the current buffer. You can call the flush method directly..
fileWriter.flush()
fileWriter.close()
You don't need to use the flush method if you are closing the file. The flush can be used for example if your program runs for a while and outputs something in a file and you want to check it elsewhere.
You need to close the filewriter else the current buffer will not flush and will not allow you to write to the file.
fileWriter.flush(); //just makes sure that any buffered data is written to disk
fileWriter.close(); //flushes the data and indicates that there isn't any more data.
From the Javadoc
Close the stream, flushing it first. Once a stream has been closed,
further write() or flush() invocations will cause an IOException to be
thrown. Closing a previously-closed stream, however, has no effect.
Closing was missing. Hence not the last buffered data was not written to disk.
Closing also happens with try-with-resources. Even when an exception would be thrown. Also a flush before close is not needed, as a close flushes all buffered data to file.
try (FileWriter fileWriter = new FileWriter("C:\\temp\\test.txt"))
{
fileWriter.write("Hi this is sasi This test writing");
fileWriter.append("test");
}
catch (IOException ioException)
{
ioException.printStackTrace();
}
Try this:
import java.io.*;
public class Hey
{
public static void main(String ar[])throws IOException
{
File file = new File("c://temp//Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
}
}
Please try this :
try
{
FileWriter fileWriter = new FileWriter("C:\\temp\\test.txt");
fileWriter.write("Hi this is sasi This test writing");
fileWriter.append("test");
fileWriter.flush(); // empty buffer in the file
fileWriter.close(); // close the file to allow opening by others applications
}
catch(IOException ioException)
{
ioException.printStackTrace();
}
Related
I have next function:
static void write()
{
try {
File file = new File ("flip.out");
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write(sMax);
System.out.println(sMax);//This command it works
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
The problem is that my program doesn't write anything in my file.
Few things to rectify -
Why create two different instances of File object
File file = new File ("flip.out");
BufferedWriter out = new BufferedWriter(new FileWriter("flip.out"));
All you need to do is
File file = new File ("flip.out");
BufferedWriter out = new BufferedWriter(new FileWriterfile(file ) ));
Next put your close call in finally statement rather than try block. Why? Because of IOException occurs resource will not be closed and if resource do not get closed your changes may not be reflected in the file.
Next it is a good programming practice not to catch Runtime exceptions. So do not use Exception as a ploymorphic type to catch your exception. Use whatever is being thrown like IOException in your case.
Now there might be various reasons why noting is being written in the file. As you are not getting and Exception one of the reason why this might be happening because your static function is not getting called or the string/object sMax(whatever that is) is empty.
Also the file(if not already present) will be created in the current directory. So if there are multiple instance is your code where your are creating files with same name then make sure you are checking the right one.
You have to flush the stream in order for what's in the memory to get written to the drive. What you wrote to BufferedWriter is sitting in a byte array waiting for the rest of it to be filled up before actually writing it to the disk. This helps with performance, but means you have to flush the stream in case you don't fill up that buffer. Here is how you do that:
static void write() throws IOException {
BufferedWriter out = new BufferedWriter(new FileWriter("flip.out"));
try {
out.write(sMax);
out.flush();
} catch (Exception e) {
// probably could ditch this and
// just the exception bubble up and
// handle it higher up.
e.printStackTrace();
} finally {
out.close();
}
}
So if it makes it to the flush() we know we wrote everything to the stream we wanted. However, if we ever get an exception we make sure we close the stream regardless of success or exception. And finally our stream is outside the try statement because the only exception ever thrown by Writers/OutputStreams during construction is FileNotFoundException which means the file never got opened in the first place so we don't have to close it.
can you call out.flush() before closing.
that will make sure any content in buffer is written to file immediately.
I am reading a file in.txt and writing the numbers to a file out.txt until 42 is found.But in out.txt I am getting blank file.Instead if I write System.out.println(num) instead of out.write(num) I get correct result.It means that the problem is with the statement of BufferedReader.Where I am wrong?
import java.io.*;
class Numbers
{
public static void main(String args[])
{
try{
String num;
BufferedReader in=new BufferedReader(new FileReader("in.txt"));
BufferedWriter out=new BufferedWriter(new FileWriter("out.txt"));
while((num=in.readLine())!=null)
{
if(Integer.parseInt(num)==42)
break;
else
out.write(num);
}
}catch(Exception e)
{
System.out.println("File not found");
}
}
}
The problem is the you are not closing the out stream. Change it to:
BufferedReader in = null;
BufferedReader out = null;
try{
String num;
in = new BufferedReader(new FileReader("in.txt"));
out = new BufferedWriter(new FileWriter("out.txt"));
while((num=in.readLine())!=null)
{
if(Integer.parseInt(num)==42)
break;
else
out.write(num);
}
out.close()
}catch(Exception e)
{
System.out.println("File not found");
}finally{
try{
if(in!=null) in.close();
if(out!=null) out.close();
}catch(Exception ex) {ex.printStackTrace();}
}
This is because, your OutputStream buffers your data and periodically flushes it. Closing the stream not only flushes it but also makes it safe for other applications to use the file.
In your case you might expect a weird behavior (with sometimes complete write and sometimes not). This is due to the fact that BufferedWriter() tries closing it in its finalize method (which may or may not be called)
You need to close your FileWriter:
while((num=in.readLine())!=null)
{
if(Integer.parseInt(num)==42)
break;
else{
out.write(num);
out.flush();
}
}
out.close();
Contents always need to be flushed. close() by itself will flush the stream for you, but it's good practice to flush() anyway.
You should close the stream after stop using it. Closing it will, firstly, flush the stream (all buffered data will be printed) and secondly, will release all resources the stream is using.
make sure you have out.close() at the end of try block.
if you have in.txt as a very big file, then you will see some data in out.txt.
BufferedWriter writes only when it has enough data to flush, which is approximately equal to one block size.
I want to write something to a file line by line.
I have the problem, that this process takes a lot of time and get canceld sometimes. The current version write the stuff to the file just at the end. Is it possible to write it to the file line by line?
E.g. if I abboard after line 4 (of 400) the file currently is empty. But I want to have the 4 line already in the file.
Here is my code:
String path = args[0];
String filename = args[1];
BufferedReader bufRdr = // this does not matter
BufferedWriter out = null;
FileWriter fstream;
try {
fstream = new FileWriter(path + "Temp_" + filename);
out = new BufferedWriter(fstream);
} catch (IOException e) {
System.out.println(e.toString());
}
String line = null;
try {
while ((line = bufRdr.readLine()) != null) {
// HERE I'm doing the writing with out.write
out.write(...);
}
} catch (IOException e) {
System.out.println(e.toString());
}
try {
out.close();
} catch (IOException e) {
System.out.println(e.toString());
}
Use the flush function when you want to make sure the data that is already been written to the writer gets into the file
out.flush()
Try out.flush() after out.write(...)
Use out.flush() after calling out.write(...).
Considering the java documentation FileWriter, you can directly write things to a file using the FileWriter, without using a BufferedWriter.
Also, as pointed out, you need to flush your datas before closing your buffer. The function write only fill your buffer, but it doesn't write to the file on the disk. This operation is done by using flush or close (to write the current content of the buffer to the disk). The difference between these two functions is that flush let's you write things after and close closes the stream definitely.
The data you write to the buffer normally will not actually be written until out.flush() or out.close() is closed. so for your requirement you should use out.flush();
I have this ArrayList files
for(File file : files){
InputStream in = FileInputStream(file);
// process each file and save it to file
OutputStream out = FileOutputStream(file);
try{
} finally {
in.close();
out.close();
}
}
the performance is really slow since every loop there is a in/out close(), is there a better way to do this? I tried to put outputstream oustide of the loop, it doesn't work.
Using buffered streams makes a huge difference.
Try this:
for(final File file : files) {
final InputStream in = new BufferedInputStream(new FileInputStream(file));
final OutputStream out = new BufferedOutputStream(new FileOutputStream(new File(...)));
try {
// Process each file and save it to file
}
finally {
try {
in.close();
}
catch (IOException ignored) {}
try {
out.close();
}
catch (IOException ignored) {}
}
}
Note that the IOExceptions that can be thrown when closing the streams must be ignored, or you will lose the potential initial exception.
Another problem is that both streams are on the same file, which doesn't work. So I suppose you're using two different files.
A close() can take up to 20 ms. I doubt this is your program unless you have 1000's of files.
I suspect your performance problem is a lack of buffering the input and output. Can you show your buffering wrappers as well?
you can of course build a queue of OutputStreams and offload that to a background thread that handles the closing of these outputstreams. Same for InputStreams.
Alternatively you can leave it down to the JVM to do that -- simply don't close the files and leave it to the GC to do that when objects are finalized.
I have a sound file that's recorded in my Java code and I need some code to delete it.
What is so special about sound file??!!!
You can use this code.
public static void deleteFile(String file){
File myFile = new File(file);
if (!myFile.delete()){
System.out.println("Deletion was not sucessful");
}else{
System.out.println("File deleted");
}
}
Since the answer is so obvious (file.delete()), I suspect that you're actually having issues with deleting it. I.e, file.delete() has returned false and the file is in reality not been deleted from the disk file system.
In that case, you can not delete it when you still have pointers open on that file. For example, when you have a InputStream or OutputStream on the file in your Java code, then you will not be able to delete the file as long as you do not call close() on the streams.
So, to fix that issue, you need to ensure that you call close() on any InputStream and OutputStream in the finally block of the try block where you're using the streams.
E.g.
File file = new File(name);
OutputStream output = null;
try {
output = new FileOutputStream(file);
// Write to output here ...
file.delete(); // Will always fail because output is not closed.
} finally {
if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
}
file.delete(); // Will succeed after close of output.