filereader - Behavior of InputStream vs. CharacterStream -
i trying understand difference between behavior of byte oriented stream (say fileinputstream) , character oriented stream (say filereader).
i went through following: http://docs.oracle.com/javase/tutorial/essential/io/charstreams.html
first program:
`import java.io.fileinputstream; import java.io.fileoutputstream; import java.io.ioexception;
public class copybytes { public static void main(string[] args) throws ioexception {
fileinputstream in = null; fileoutputstream out = null; try { in = new fileinputstream("xanadu.txt"); out = new fileoutputstream("outagain.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
} ` second program:
import java.io.filereader;
import java.io.filewriter; import java.io.ioexception;
public class copycharacters { public static void main(string[] args) throws ioexception {
filereader inputstream = null; filewriter outputstream = null; try { inputstream = new filereader("xanadu.txt"); outputstream = new filewriter("characteroutput.txt"); int c; while ((c = inputstream.read()) != -1) { outputstream.write(c); } } { if (inputstream != null) { inputstream.close(); } if (outputstream != null) { outputstream.close(); } } }
}
it says: in copycharacters, int variable holds character value in last 16 bits; in copybytes, int variable holds byte value in last 8 bits.
my question is: wanted check above sentence printed value of c (integer defined in program) while being copied. value of c must different @ consecutive reads because in byte stream reads byte byte, have byte value, while in character stream reads character character, has character ascii value. giving same values of c. why?
tried think in different way, if source file has 1 character 'a'.
now copybytes should run while loop atleast 2 times because character takes 2 bytes. running once.
import java.io.filereader;
import java.io.filewriter; import java.io.ioexception; //in copycharacters, int variable holds character value in last 16 bits; //in copybytes, int variable holds byte value in last 8 bits.
public class copycharacters { public static void main(string[] args) throws ioexception {
filereader inputstream = null; filewriter outputstream = null; try { inputstream = new filereader("source.txt"); outputstream = new filewriter("characteroutput.txt"); int c; while ((c = inputstream.read()) != -1) { system.out.println("one"); outputstream.write(c); } } { if (inputstream != null) { inputstream.close(); } if (outputstream != null) { outputstream.close(); } } }
}
here 1 printed once
Comments
Post a Comment