java - OutputStreamWriter vs FileWriter -


i don't understand difference between these 2 classes. when use 1 on one? know filewriter can output characters file can outputstreamwriter far know. here code tested , seem work same, i'm not adding exception handling stuff lets assume there.

filewriter writer = new filewriter("c:\\users\\owner\\desktop\\demo.txt"); writer.write("hello"); writer.close(); 

i tried code:

file file = new file("c:\\users\\owner\\desktop\\demo.txt"); os = new outputstreamwriter(new fileoutputstream(file)); os.write("hello"); os.close(); 

both of these seem work same me. time strange happens when try put int value in write() method. filewriter example, demo.txt empty. outputstreamwriter example weird symbols in text file. reading java book , explanation outputstreamwriter "converts stream of characters stream of bytes" shouldn't seeing bytes in text file in second example?

some clarification appreciated.

xxxinputstream , xxxoutputstream (where xxx varies, there's lot of options) deal 8-bit bytes. example, outputstream.write(byte[] c);

xxxwriter or xxxreader deal 16-bit chars. example, reader.read(char[] cbuf).

outputstreamwriter converts outputstream writer. may have guessed, inputstreamreader converts inputstream reader. unaware of classes reverse, i.e. convert reader inputstream.

filewriter writer talks files. since java string internally uses chars (16 bit can handle unicode), filewriter natural class use unicode strings.

fileoutputstream outputstream writing bytes file. outputstreams not accept chars (or strings). wrapping in outputstreamwriter have writer, accept strings.

now, real question, when use reader/writer , when stream? i've used java years , confused too. believe following correct:

handy guide - how decide use:

  1. if dealing binary data (e.g. image) use streams.
  2. if using non-ascii unicode characters, e.g. chinese, use readers/writers.
  3. if using ordinary ascii text (the traditional 0-127 characters) can (usually) use either.

some other links:

inputstream , reader in java io

inputstream vs inputstreamreader


Comments