Reputation: 301
The new test1.txt file this program creates is completely empty, the original file test.txt is filled with something like "50 3 21 57 10 20", basicly integers with whitespace between them.
import java.util.*;
import java.io.*;
class AddOneToInts
{
public static void main(String [] args) throws IOException
{
Scanner scan = new Scanner(new BufferedReader(new FileReader( "test.txt" )));
BufferedWriter writer = new BufferedWriter(new FileWriter( "text1.txt" ));
boolean cont = true;
String temp;
while (cont) {
if (scan.hasNextInt()) {
temp = (scan.nextInt()+1) + " ";
writer.write(temp);
} else break;
}
}
}
Upvotes: 1
Views: 85
Reputation: 81588
Best practice for closing stream:
import java.util.*;
import java.io.*;
public class AddOneToInts
{
public static void main(String [] args) throws IOException
{
Scanner scan = null;
BufferedWriter writer = null;
try
{
scan = new Scanner(new BufferedReader(new FileReader( "test.txt" )));
writer = new BufferedWriter(new FileWriter( "text1.txt" ));
boolean cont = true;
String temp;
while (cont)
{
if (scan.hasNextInt())
{
temp = (scan.nextInt()+1) + " ";
writer.write(temp);
}
else break;
}
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if(writer != null)
{
try
{
writer.close();
}
catch(IOException e) {}
}
if(scan != null)
{
try
{
scan.close();
}
catch(IOException e) {}
}
}
}
}
Although Apache Commons-IO has a function that can "close the stream silently" so you don't have to write the second try-catch block in the finally block.
Upvotes: 1
Reputation: 196
I can see the question has been answered for the asker already. Just for the benefit of anyone looking at this later for similar stream related issues, thought will try to add some more clarity. What was missing was an effective
writer.flush()
A BufferedWriter (or any Writer which buffers) flushes automatically when its buffer is full. I guess the normal size is around 8K. That is why it did not auto-flush in this case.
A writer.close()
does a buffer flush()
. So close() works.
However, for a native stream on process exit, it automatically does a close()
. Here it was not a native one instead it was a higher level buffer. To illustrate if the following replacements were made in the example,
//OutputStreamWriter writer=new OutputStreamWriter(new FileOutputStream("text1.txt"));
OutputStream out=new FileOutputStream("text1.txt");
and
//writer.write(temp);
out.write(temp.getBytes());
it would not even require a flush() or close() for this example to work - though that was the right thing to do.
Upvotes: 1
Reputation: 8338
You have to close the stream for Java to flush its contents to the file:
Scanner scan = new Scanner(new BufferedReader(new FileReader( "test.txt" )));
BufferedWriter writer = new BufferedWriter(new FileWriter( "text1.txt" ));
boolean cont = true;
String temp;
while (cont) {
if (scan.hasNextInt()) {
temp = (scan.nextInt()+1) + " ";
writer.write(temp);
} else break;
}
writer.close(); // <<------------------------
Upvotes: 1