Tags: code, file_path, fileoutputstream, fileoutputstreamprivate, filewriter, final, gohan, htm, java, programming, snippets, static, string

FileWriter vs FileOutputStream

On Java Studio » Java Programming

2,746 words with 1 Comments; publish: Tue, 18 Sep 2007 19:36:00 GMT; (15062.50, « »)

i have this two code snippets....

first is the FileOutputStream

private static final String FILE_PATH= "d:\\gohan\\test.htm";

FileOutputStream fw = new

FileOutputStream(FILE_PATH);

BufferedReader in = new BufferedReader(new InputStreamReader(transferSocket.getInputStream()));

int i = in.read();

while(i != -1)

{

fw.write(i);

i = in.read();

}

second is the FileWriter

private static final String FILE_PATH= "d:\\gohan\\test.htm";

FileWriter fw = new FileWriter(FILE_PATH); BufferedReader in = new BufferedReader(new InputStreamReader(transferSocket.getInputStream()));

int i = in.read();

while(i != -1)

{

fw.write(i);

i = in.read();

}

why is it that when i used the FileWriter class here i can't write into the file (the file says 0 kb when in fact im writing 30 kb into it) but when i used the FileOutputStream it works! I can write into the specified file. What seems to be the difference? When should one use the FileWriter or the FileOutputStream class?....calling some SCJP people out there......

All Comments

Leave a comment...

  • 1 Comments
    • Hi,

      FileWriter is basically used to write as characters instead of writing as bytes they are called Character streams.

      The FileWriter Write characters to an output stream, translating characters into bytes according to a specified character encoding. Each OutputStreamWriter incorporates its own CharToByteConverter, and is thus a bridge from character streams to byte streams.

      The encoding used by an OutputStreamWriter may be specified by name, by providing a CharToByteConverter, or by accepting the default encoding, which is defined by the system property file.encoding.

      Each invocation of a write() method causes the encoding converter to be invoked on the given character(s). The resulting bytes are accumulated in a buffer before being written to the underlying output stream. The size of this buffer may be specified, but by default it is large enough for most purposes.

      While in the case of FileOutputStream the writing to the file occurs immediately but in the case of FileWriter its first stored in a buffer and then written to file.When u use FileOuputstream u write into a file as bytes.

      So adding the following line to ur code involving FileWriter will ensure immediate writing to the file.

      FileWriter fw = new FileWriter(FILE_PATH); BufferedReader in = new BufferedReader(new InputStreamReader(transferSocket.getInputStream()));

      int i = in.read();

      while(i != -1)

      {

      fw.write(i);

      i = in.read();

      fw.flush();

      }

      Hope that helps

      Regards,

      Partha

      #1; Tue, 03 Jul 2007 12:22:00 GMT