CODE
import java.io.*;
class BufferedOutputStreamDemo
{
public static void main(String arg[])
{
File source = new File("E:JavaPrograms\\FolderOne\\fileOne.txt");
// LINE A
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(source));
if(source.exists())
{
System.out.println("File exists.");
byte b[] = {'M','E','R','I','T',' ' ,'C','A','M','P','U','S'};
// Writing into file fileOne
bos.write(b); // LINE B
bos.flush(); // LINE C
bos.close();
}
else
System.out.println("File not found.");
//bos.close();
//Now retrieving data from fileOne
// LINE D
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(source));
int c =0;
while((c = bis.read())!= -1)
System.out.print((char)c);
bis.close();
}
}
File exists.
MERIT CAMPUS
At LINE A
we created a BufferedOutputStream
object.
At LINE B
we are writing the bytes in array b
to file source
At LINE C
we are flushing out the bytes in the BufferedOutputStream
and ensuring no more bytes in BufferedOuputStream
.
At LINE D
we created a BufferedInputStream
object to retrieve bytes from file source
and printing them.
close
method in if
and else
block and see the output. No ouput is displayed since the BufferedOutputStream
object is still holding the file. So whenever the action is completed close the streams.I LOVE JAVA
in to source using write(int)
method.