Wednesday, October 17, 2012

Java Tidbits ...................wrinting streams to file

The other low level ways to write  bytes into File rather than chars  requires the use of stream classes.
Like reading image data and writing into file . 

Hierarchy of stream classes is published on previous post.

To write byte or character stream into File we need  instance of OutputStream 
ie: ObjectOutputStream or FilterOutputStream  or FileOutputStream

OutputStreamWriter opts = new OutputStreamWriter( OutputStream opt); 

1) FileOutputStream fops = new FileOutputStream(f, true);
    OutputStreamWriter opts = new OutputStreamWriter(fops);   // fops instanceof OutputStream
        opts.write(97);
        opts.close();


public BufferedOutputStream(OutputStream out , in size)  // size is optional
2) BufferedOutputStream bf = new BufferedOutputStream(fops);
        bf.write(66);
        bf.close();


3) Pipe any instance of Outputstream to DataOutputStream       bf or fops both qualifies
        DataOutputStream df = new DataOutputStream(bf);   // from (2) bf instance of OutputStream
        df.write(67);
        df.close();

flexibility given in DataOutputStream is its instace can write  double , int , boolean float etc too the writer .
        df.writeBoolean(new Boolean(true));
        df.writeDouble(34.12);

4) use of PrintStream with file as argument will override the whole file.
     PrintStream pf = new PrintStream(f); // override file
        pf.write(68);
        pf.close();


piping it to any outputstream will prevent it from overriding .

5) PrintStream pf = new PrintStream(fos,true);
        pf.write("hello");
        pf.close();

It has very specific methods for writing , formatting , printing text into file.
6)
   BufferedWriter bw= new BufferedReader(fow);  // Writer
   we can wrap printwrite into bufferwriter  and reverse too
   BufferedWriter bw = new BufferedWriter(pos);  // allowed
   PrintWriter pos = new PrintWriter(bw);  // allowed


   we can write a new line character by using bufferwriter .

No comments: