Author Topic:   char = 1 byte ?? full code from jawroski quiz
posted April 30, 2000 08:11 PM             
this is question from jawroski which says char = 1 byte how is it possible ?

here is the full code from jawroski quiz i am adding

How many bytes does the fallowing program write to temp.txt?
public class TestIOApp{
public static void main(String args{})throws IOException{
FileOutputStream outStream = new FileOutputStream("text.txt");
String s = "text";
for(int i =0 ;ioutStream.write(s.charat(i));

edward man
posted April 30, 2000 10:09 PM           
Here is the prototype of the write method for FileOutputStream:
public native void write(int b) throws IOException

The API documentation says:
Writes the specified byte to this file output stream. Implements the write method of OutputStream.

If you are writing a char to the output stream using some other methods, the no. of bytes written will be different. However, here the method only writes one byte. It internally gets the last 8 bits (the char is promoted to int when passed as an argument) and then writes to the output stream. It does not mean that 1 char = 1 byte.

maha anna
posted April 30, 2000 10:30 PM             
FileOutputStream's write(int i) method writes only the lower 8 bits out of the 32 bit int input arg value. Since you write the String "text" ,totally 4 bytes are written to file "text.txt". Simillary while reading, FileInputStream reads ONLY ONE byte at a time and, returns the single read byte from file, as an 'int'. All higher 24 bits are put as 0 (zero bits).

I have slightly modified your code. It writes the String "text" to "text.txt" file and reads it back from the file and prints it.

maha anna

class test{
public static void main(String args[])throws IOException{
FileOutputStream outStream = new FileOutputStream("text.txt");
String s = "text";
for(int i =0 ;i < s.length();++i)

FileInputStream inStream = new FileInputStream("text.txt");

int i=0;

while( ( > 0)



[This message has been edited by maha anna (edited April 30, 2000).]