一、如何用字节流读取文件

read的几种参数写法

public static void main(String[] args) throws IOException {
//定义自己的文件路径
File file = new File("D:"+File.separator+"inputstream"+File.separator+"inputenglish.txt");
//创建一个输入流,这里会报异常,所以用throws或者try-catch,最好是try-catch然后在finally中去关闭,此时的in是一个文件内容的读取流
InputStream in = new FileInputStream(file);
//输出首地址
System.out.println(in);
//★read();读取一个字节,返回读取的字节,这里的read()是不带参数的,read共有三种读取方式
int data1 = in.read();
//因为是字节流,所以如果不带(char),则输出的就是第一个字节的asicⅡ码值,加上了(char)就是首个字节对应的char
System.out.println((char)data1);
//★★read(byte[] b):读取多个字节保存到数组b中,这个是read的另外一个带参数的用法
//首先需要定义一个byte数组来接收从inputstream中读取的字节流
byte[] buffer = new byte[100];
in.read(buffer);
//输出的是字节数组,★★★这里我们可以看到之前已经输出的一个字节再接下来的输出中就不会继续输出,如文件中的字符串是abc,那么因为已经输出了第一个字节,那么接下来的输出就只有bc,有点类似于先生成一个流,然后大家排队消费,排在前面已经消费过的字节不能再继续被消费
System.out.println(Arrays.toString(buffer));
//输出的是对应的字节,文件中的内容
System.out.println(new String(buffer));
//读完了记得关闭
in.close();
//★★★★上面我们说了排在前面已经消费过的字节不能再继续被消费,如果想要重新消费怎么办?很简单,重新创建一个流就好了。
InputStream in2 = new FileInputStream(file);
//这里写的不好,因为byte数组的大小写死了,如果文件的内容有200该怎么办呐?
byte[] buffer2 = new byte[100];
in2.read(buffer2);
System.out.println(new String(buffer2));
//上面的方法还没有办法支持读取中文文本的读取
针对第四点读取固定长度,没有办法读取全部内容的优化
public String ReadFileM(String filepath) throws IOException{
//获取输入流
File file = new File(filepath);
InputStream in = new FileInputStream(file);
byte[] buffer = new byte[20];
int length = 0;
//这里使用StringBuffer,因为用StringBuffer对字符串进行拼接效率更好
StringBuffer sBuffer = new StringBuffer();
//方法解释中的-1相当于是数据字典告诉调用者文件已到底,可以结束读取了,这里的-1是int型,方便读取只能将8为字节转为10进制的数
while ((length = in.read(buffer)) != -1) {
//也能按照文件格式把数据读取出来,但是没有办法把它输出的内容当成一个字符串来操作,所以需要下面sBuffer.append
//System.out.println(new String(buffer, 0, length));
//System.out.println("每20个一读");
//这里while循环判断length = in.read(buffer)是否为-1,while循环成立的时候,每次都读20个大小的字节,最后一次可能小于20,再下一次肯定是-1,所以循环成立,进入执行,每次加新的字节,加哪些字节,读取的buffer,从buffer的哪里加,从0的位置一直到length的位置
sBuffer.append(new String(buffer, 0, length));
}
in.close();
//System.out.println(sBuffer.toString());
return new String(sBuffer);
}
二、用字节流完成文件的复制
public void FileCopy(String srcpath, String descpath) throws IOException{
//获取文件对象
File srcFile = new File(srcpath);
File descFile = new File(descpath);
//创建输入输出流
InputStream in = new FileInputStream(srcFile);
OutputStream out = new FileOutputStream(descFile);
//读取和写入操作
byte[] buffer = new byte[10];
int len = -1;
while ((len = in.read(buffer)) != -1) {
System.out.println(new String(buffer,0,len));
out.write(buffer,0,len);
}
out.close();
in.close();
}
本文详细介绍了如何使用字节流读取文件,包括不同read方法的使用及注意事项,以及如何优化读取过程以支持大文件和中文文本的读取。此外,还讲解了如何利用字节流完成文件的复制。
2122

被折叠的 条评论
为什么被折叠?



