writing to a file, but not just at the end - java

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();

Related

Error where FileOutputStream only writes to file after the program has been terminated

I've had this error in the past but never fully understood it. After closing an OutputStream, regardless of the location of the java file or the manner in which it is called, completely screws up all sequential runs or attempts to write to another file, even if a different method of writing to a file is used. For this reason I avoid closing streams even though it is a horrible habit not to. In my program, I created was trying a test case that had a close statement which destroyed all of my previous streams, making it for some reason that they only write to files after the program has been terminated.
I kept the file location open and it writes the Text in the text file at the appropriate time, however the "Preview" panel in Windows does not detect it (which used to happen). Note that this all worked perfectly before the stream was accidentally closed. Is there a manner to reset the stream? I've tried flushing it during the process but is still does not run as it did prior.
Here is the method used to create the file:
protected void createFile(String fileName, String content) {
try {
String fileLoc = PATH + fileName + ".txt";
File f = new File(fileLoc);
if(!f.isFile())
f.createNewFile();
FileOutputStream outputStream = new FileOutputStream(fileLoc);
byte[] strToBytes = content.getBytes();
outputStream.write(strToBytes);
} catch (IOException e) {
e.printStackTrace();
return;
}
}
as well as the method used to read the file:
protected String readFile(String fileName) {
try {
StringBuilder sb = new StringBuilder("");
String fileLoc = PATH + fileName + ".txt";
File f = new File(fileLoc);
if(!f.exists())
return "null";
Scanner s = new Scanner(f);
int c = 0;
while(s.hasNext()) {
String str = s.nextLine();
sb.append(str);
if(s.hasNext())
sb.append("\n");
}
return sb.toString();
} catch(Exception e) {
e.printStackTrace();
return "null";
}
}
I'd be happy to answer any clarification questions if needed. Thank you for the assistance.
without try-resource, you need close in final clause to make sure no leak. Or use Stream.flush() if you need more 'in-time' update.
} catch (IOException e) {
e.printStackTrace();
return;
} finally {
outputStream.close();
}
You need to call flush() on the stream to write the bytes to the stream.
You're currently calling write() by itself, like this:
FileOutputStream outputStream = new FileOutputStream(fileLoc);
outputStream.write(content.getBytes());
What you want to do is this:
FileOutputStream outputStream = new FileOutputStream(fileLoc);
outputStream.write(content.getBytes());
outputStream.flush();
From the Javadoc (https://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html#flush--) for OutputStream (where FileOutputStream is an OutputStream), this is what it says for flush():
Flushes this output stream and forces any buffered output bytes to be written out. The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination.
Even better would be to close the stream in a finally block, so that no matter what your code always tries to free up any open resources, like this:
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(fileLoc);
outputStream.write(content.getBytes());
outputStream.flush();
} finally {
if (outputStream != null) {
outputStream.close();
}
}
or use automatic resource management, like this:
try (FileOutputStream outputStream = new FileOutputStream(fileLoc)) {
outputStream.write(content.getBytes());
outputStream.flush();
}

BufferedWriter not writing anything to a file

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.

Not able to write into the file

I am trying to create a file and keep on appending into that file. In my code file is getting created but It is not appending anything in that file. Don't know why? Can anyone suggest me what wrong I am doing..
Updated Code:-
File file =new File("D://GeoData1.txt");
BufferedWriter out = new BufferedWriter(new FileWriter(file, true));
int j = -1;
while(true) {
j++;
String ipAddress = generateIPAddress(j);
try {
out.write(ipAddress);
System.out.println(ipAddress);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You should close the file or flush buffers I guess.
Are you closing the writer?
finally {
bufferWritter.close();
}
Update:
If you are using Java 7, try this:
final int NUMBER_OF_IPS_TO_APPEND = 5000; // or whatever size
Charset charset = Charset.defaultCharset();
Path file = Paths.get("myfile.txt");
try (BufferedWriter writer = Files.newBufferedWriter(file, charset,
StandardOpenOption.CREATE,
StandardOpenOption.APPEND)) {
for (int i = 1; i <= NUMBER_OF_IPS_TO_APPEND; i++) {
String ip = generateIPAddress(i);
System.out.printf("Generated ip: %s\n", ip);
writer.append(ip + "\n");
}
} catch (IOException x) {
System.err.format("IOException: %s\n", x);
}
Code adapted from The Java Tutorials.
Check if the IPS are being printed to the console and the file.
Fully working code with a mock implementation of generateIPAddress. It appends 5000 random IPv4 addresses (not checking for validity) to myfile.txt everytime it is executed.
I would try just passing the file writer the file object and getting rid of the .getName()
BufferedWriter out = new BufferedWriter(new FileWriter(file, true));
You have infinite loop with while(true). You should make a break point with a statemant or make the the "while" loop like while(i < xy)....
First of all, the loop is never-ending. You should at least make it stop at some point.
Also, you need to close the file to free any memory. Hope it helps!
--edit--
To close a file, its
file.close();
If you want to see the changes made to the file during the time the program is running you need to flush the writer. Please note that sooner or later it will be flushed automatically. The reason why you don't see changes in your text editor depends on your editor. For instance it is not able to open such big file (please note that in your program you are appending chars to this file very fast). Check the size of the file. If the size is increasing then it works.
If you want to monitor the file you can use tools like tail.

how can you delete a sound file in java?

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.

Problem writing to file

I'm having a problem writing to a file:
FileInputStream fin;
try
{
fin = new FileInputStream ("c:/text.txt");
PrintStream p = new PrintStream(fin);
p.println ("test");
fin.close();
}
catch (IOException ioe)
{
System.err.println (ioe.getMessage);
}
Is there a problem with this code?
You need to use a FileOutputStream.
Get used to the following structure. You'll use it a lot in Java.
PrintStream out = null;
try {
out = new PrintStream(new FileOutputStream("c:/text.txt"));
out.println ("test");
} catch (IOException e) {
System.err.println (e.getMessage);
} finally {
if (out != null) {
try { out.close(): } catch (Exception e) { }
}
out = null; // safe but not strictly necessary unless you reuse fin in the same scope
}
At least until ARM blocks hopefully eventuate in Java 7.
As noted, you should close the PrintStream and not the FileOutputStream so the above is a better form to use.
Problems with that code that immediately strike me:
Non-standard formatting.
Awkward variable names.
The exception handling is not good.
Failure to close the file in the case of exceptions. (Use acquire(); try { use(); } finally { release(); }.
Hidden use of default character encoding.
PrintStream swallows exceptions. BufferedOutputStream is better.
Failure to flush the decorator. It may still have data buffered. Although actually in this case you have left the PrintStream in auto-flush mode, which can be a performance issue.
Use / for a Windows path separator. You might be able to get away with it, but it's not good.
So:
FileOutputStream fileOut = new FileOutputStream(
"c:\\text.txt"
);
try {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
fileOut,
"UTF-8" // Or, say, Charset.defaultCharset()
));
out.write("test");
out.newLine()
out.flush();
} finally {
fileOut.close();
}
The class: FileInputStream is used to read input from a file. If you want to write to the file, you can use: FileOutputStream. If you want to make your life really easy, you can use a BufferedOutputStream as well.
As pointed out, you should close your streams in the finally block. The reason why you want to do that is say your program isn't really small, and it's a larger application. If you forget to close file streams, for example, the application will hold on to it and if you try to do something to it on the file system (read: at least in Windows) you won't be able to it. We've all seen the 'File cannot be deleted because it's still in use' error.
Here's an example of using the FileOutputStream + BufferedOutputStream: http://www.javadb.com/write-to-file-using-bufferedoutputstream.

Categories

Resources