您的位置:首页 > 编程语言 > PHP开发

理解inputstream和outputstream

2017-01-09 17:02 337 查看
注意reader/writer和inputstream/outputstream的区别,其实说白了,就是字符操作和字节操作。

public class FileCount {

public static void main(String[] args) throws IOException {

//可以两个字节一起读
//byte[] buffer = new byte[2];

int count = 0;

InputStream inputStream = null;

try {
inputStream = new FileInputStream(new File("/Users/lixiang/workspace/text2.txt"));

//while(inputStreamReader.read(buffer) != -1
while (inputStream.read() != -1){
count ++;
}

System.out.println( "----长度是" + count + "字节");
} catch (IOException e){
e.printStackTrace();

} finally {
inputStream.close();
}
}
}

读取的文件内容,如下图:



上面的代码,read方法默认读取一个字节,而上述文件中看上去只有4个英文字母也就是4个字节,但是实际上却输出6个字节,原因是每行末尾都有一个回车符占用一个字节的大小。

如果不想使用read方法一次只读取一个字节,可以用注释当中的内容,替换掉下一行,注释中,代表着一次读取两个字节大小的内容。

再贴个inputstream子类fileinputstream的例子:

public class FileCopy {

public static void main(String[] args) {

byte[] buffer = new byte[2];

int numberRead = 0;

FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;

try {

fileInputStream = new FileInputStream("/Users/lixiang/workspace/text2.txt");
fileOutputStream = new FileOutputStream("/Users/lixiang/workspace/text1.txt");

//fileinputstream.read(byte[]) 返回的内容是byte的大小,如果读到结尾就-1

while ((numberRead = fileInputStream.read(buffer)) != -1) {

//mdzz next line 这个fileInputStream.read() 会造成跳行读取文件
//System.out.println(fileInputStream.read(buffer));

System.out.println(numberRead);
fileOutputStream.write(buffer, 0, numberRead);
}
} catch (IOException e) {
e.printStackTrace();
} finally {

try {
fileInputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

这里注意,fileinputstream的read方法在这个类中被重写了,父类的方法在子类方法中被重写了。
调用了native readbytes方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: