IO操作-FileInputStream和FileWriter以及对应的out Reader

62 阅读2分钟

概述

Java中的流操作一般分为两种类型,字节流操作和字符流操作。字节流对应的是byte为单位进行数据的读取,字符流对应char为单位进行数据的读取

FileInputStream

这个类是对应于字节流,利用File对象构建输入流对象

读取方式--单个字节读取

public int read() throws IOException

这个方法返回到的是读取到的字节数据,同时要循环读取

int read = 0;
while (((read = fileInputStream.read()) != -1)) {
    System.out.print((char) read);
}

读取方式--多个字节读取

public int read(byte b[])

这个方法就是把数据读取到缓存b中,同时返回究竟读取了多少个字节的数据,因此一般这样读取

byte[] bytes = new byte[20];
int length = 0;
while (((length = fileInputStream.read(bytes)) != -1)) {
    System.out.print(new String(bytes, 0, length));
}

FileOuputStream

这个方法主要是用来写的 一般用到的方法是

public void write(byte b[])

具体的重载方法还有很多,其实都是一个方法就是传入byte数组,然后确定好写入的起止index。

public void write(byte b[], int off, int len)

利用FileInput/OutputStream完成文件拷贝

FileInputStream fileInputStream = new FileInputStream(resourceFilepath);
byte[] buffer = new byte[1024];
int readLength = 0;
FileOutputStream fileOutputStream = new FileOutputStream(outputFilepath,true);
while (((readLength = fileInputStream.read(buffer)) != -1)) {
    fileOutputStream.write(buffer, 0, readLength);
}
fileInputStream.close();
fileOutputStream.close();

FileReader

读取也是两种方式,单个字符读取和多个字符一起读取

public int read()
public int read(char cbuf[])

FileWriter

写入也是两种,单个字符写入和多个字符一起写入

public void write(int c)
public void write(char cbuf[], int off, int len)

但是要注意一点,写完了以后记得flush 要不写不进去

FileWrite/Reader完成文件拷贝

FileReader fileReader = new FileReader("/Users/zhangzhiwei/Desktop/JavaWeb学习资料/代码/hspedu_javaweb/css/2.use-css-style.html");
char[] chars = new char[10];
int readLength = 0;

FileWriter fileWriter = new FileWriter("/Users/zhangzhiwei/Desktop/zz/t1.txt", true);
while (((readLength = fileReader.read(chars)) != -1)) {
    fileWriter.write(chars, 0, readLength);
}
fileWriter.close();
fileReader.close();

感觉都一样