Reputation: 613
I am new in Java. I am learning the fileIO. I was writing a little program to display the content in a txt file. My code is as follow :
import java.io.*;
public class Readf {
public static void main(String arg[]) throws IOException {
FileInputStream in = null ;
try {
in = new FileInputStream("input.txt");
int c;
String cs="";
while ((c=in.read())!=-1) {
cs = cs + (char)c;
if ((char)c=='\n') {
System.out.println(cs);
cs="";
}
}
} finally {
if (in != null) {
in.close();
}
}
}
}
I was reading an online tutorial. It told me to read the file with an int variable. Since I wanted to display the content in char, I cast them into char type and store it into a sting and it WORKED!!!! In Java, a int variable is 32-bit but a char variable is 16-bit. I cast them into 16bit char every time I read an 32bit int. Why the result wasn't a chaos?
Upvotes: 1
Views: 166
Reputation: 1061
Check read() method description in FileInputStream class:
As you can see in specification, a read method "Reads a byte of data from this input stream" which means all your ints in your program (c variable) will always be less than or equal to 255 and greater that or equal to 0. It doesn't matter if you read txt file or pdf, png etc.
You can check it by trying to print something when c is greater than 255, eg.:
if (c > 255) {
System.out.println("c>255");
}
and "c>255" will never be printed.
Because int is signed you can also check if c is less than zero.
if (c < 0) {
System.out.println("c<0");
}
and again "c<0" will never be printed as well.
Only last int will be -1 of course.
So every int from a range <0, 255> can be safely cast to char without loosing any information.
Upvotes: 1
Reputation: 983
Actually, I respect your insistence to understand rather than to just get the desired output.
The catch is that each character you scan has an ascii value below 2^8 which makes it fits in int
32-bit and fits in char
16-bit.
The chaos you are taking about will appear in the case an ascii value fits in 32-bit but not in 16-bit which will not exist in ascii character set but in unicode.
Upvotes: 0
Reputation: 2953
All the characters you will possibly keep in your file will be well within the range of 16 bit unicode character set which java works upon. Hence there should not be any problem converting a char(16 bit) to an int(32 bit) or vice versa.
Upvotes: 0