在复习Java的输入/出流,用FIieInputStream读取文件的时候,如果每次读取一个字节发现无法读取文件全部内容,但用字节数组的方式读取却没有错误,在csdn上发问题求教以及google之后终于弄明白了。最基本的输入/出流都忘记了……在此记下,方便复习。
在用下面的代码读取的时候,readByChar()没有问题,readByByte()当按照字节数组的方式读取的时候也没有问题,但是当每次读取一个字节的时候就会有问题。
比如读取的文件内容如下图:
当每次制度去一个字节的时候输出如下图:
原因是因为:最后一行的数据在缓冲区里没有被输出
参考这里的Javadoc-PrintStream和这里的stackoverflow的一个提问。
可以看到System.out(一个PrintStream对象)只在一下三种情况下提供autoFlush:
- System.out.println ()
- 写入一个换行符或字节 (指’\n’的字节表示)
- 写入byte数组
其它的情况System.out不会提供autoFlush,需要调用System.out.flush();
,或者使用上述方法中的一种让其自动autoFlush。
代码如下:
package firPrj;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class FileReaderClass {
public static void main(String []args){
//File file = new File("c:\\","file.txt");
FileReaderClass fileReader = new FileReaderClass();
System.out.println("readByChar:");
fileReader.readByChar("c:\\file.txt");
System.out.println("");
System.out.println("readByByte:");
fileReader.readByByte("c:\\file.txt");
}
private void readByChar(String fileName){
BufferedReader br = null;
try{
br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
//br = new BufferedReader(new FileReader(fileName));
String tem = null;
while((tem=br.readLine()) != null ){
System.out.println(tem);
}
}catch(IOException e){
e.printStackTrace();
}finally{
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param fileName
*/
private void readByByte(String fileName){
InputStream in = null;
try{
in = new FileInputStream(fileName);
//******读取多个字节******
// byte []tem = new byte[2];
// int len=-1;
// while((len=in.read(tem)) != -1){
// System.out.write(tem,0,len);
// }
int tem = -1;
while((tem = in.read()) != -1){
System.out.write(tem);
}
//******问题在这里,调用flush()刷新缓冲区即可******
//System.out.flush();
//System.out.println();
} catch(IOException e){
e.printStackTrace();
} finally{
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}