学习java有一段时间了,今天学到了IO流,看到了关于IO流的一些知识,今天发一发自己对IO流的一些认识。
InputStream是输入流,字节流,节点流
示例一:
import java.io.*;
public class TestInputStream {
public static void main(String[] args) {
int b = 0;
InputStream is = null;
try {
is = new FileInputStream("g://sunshine//1.txt");
} catch(FileNotFoundException e) {
e.printStackTrace();
}
try {
while((b=is.read()) != -1) {
System.out.print((char)b + " ");
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
输出结果为:
? ? ? ? ? ? ? ? ? ? ? ¨´ ? ? ¡ã ? ? ? 1 2 3 4 5 6 7 8 9
1.txt中的内容为:
一二三四五六七八九 1 2 3 4 5 6 7 8 9
分析:
InputStream为输入流,字节流,节点流。
因为是字节流,所以每次只能读取一个字节 每读取一个字节就把它打印出来 所以在读取汉字的时候就不能正确显示
与下面的代码比较,观察输出结果有什么不同:
import java.io.*;
public class TestReader {
public static void main(String[] args) {
FileReader fr = null;
try {
fr = new FileReader("g://sunshine//1.txt");
} catch(FileNotFoundException e) {
}
int b = 0;
try {
while((b=fr.read()) != -1) {
System.out.print((char)b + " ");
}
} catch(IOException e) {
}
}
}
输出结果为:
一 二 三 四 五 六 七 八 九 1 2 3 4 5 6 7 8 9
分析:
Reader 是字符流,每一次读取一个字符,所以能将汉字正确显示到屏幕上