目录
回顾: FileInputStream / FileOutputStream
在Java中如何以二进制字节的方式处理文件?
InputStream / Outputstream: 这是基类,是抽象类;
FileInputStream / FileOutputStream: 输入源和输出目标都是文件的流。
ByteArrayInputStream / ByteArrayOutputstream: 输入源和输出目标都是字节数组的流。
BufferedInputStream / BufferedOutputstream: 装饰类,对输入输出流提供缓冲功能。
InputStream 是抽象类,主要方法有:
public abstract int read() throws IOException;
read方法是从流中读取下一个字节。一次只读取一个字节,返回值的类型是int,取值为0~255;当读到列的结尾时返回-1;如果流中没有数据,read方法会阻塞知道数据到来、流关闭或者抛出异常,当有异常出现时read()会抛出一个受检异常,类型为IOException,调用者必须处理;
public int read(byte b[]) throws IOException;
该方法一次可以读取多个字节,读入的字节会放到byte数组中,第一个字节存入byte[1],第二个字节存到byte[1]中,以此类推,一次最多读入的字节个数为数组b的长度,但实际可能少于数组的长度,返回值就是实际读入字节的个数,如果刚开始读就到结尾,返回值为-1,如果流中没有数据,他就会阻塞,异常出现时会抛处类型为IOException的异常;批量读取还有一个方法重载:
public int read(byte b[], int off,int len)throws IOException;
这个方法会将读取的第一个字节放到byte[off]位置,最多读取len个字节;
流读取结束后应该关闭,已释放相应的资源,关闭方法为:
public void close() throws IOException;
OutputStream也是抽象类,主要方法有:
public abstract void write(int b)throws IOException;
这个方法是向流中写入一个字节,参数类型为int类型;OutputStream还有两个批量写入的方法,方法作用于上面对应:
- public void write(byte b[]) throws IOException;
- public void write(byte b[],int off,int len) throws IOException;
OutputStream还有两个方法:
- public void flush() throws IOException;
- public void close() throws IOException;
flush() 方法将缓冲而未实现写的数据进行实际写入,比如在BufferedOutputStream中,调用flush会将其缓冲区的内容写到其装饰的流中,基类OutputStream和FileOutputStream中没有重写flush方法,因为他们没有缓冲区;
close()方法一般会首先显示调用flush()方法,然后在释放流所占的系统资源;
FileOutputStream和FileInputStream的输入和输出目标都是文件;
FileOutputStream的构造方法:
- public FileOutputStream(File file,boolean append)throws FileNotFoundException;
- public FileOutputStream(String name)throws FileNotFoundException;
File类型的参数file和字符串的类型参数name都表示文件路径,路径可以是绝对路径,也可以是相对路径,如果文件中已存在,append参数指定是追加还是覆盖,true表示追加,false表示覆盖,第二个构造方法没有append参数,表示覆盖。new一个FileOutputStream对象会实际打开文件,操作系统会分配相关资源,如果当前用户没有写的权限,就会抛出异常SecurityException;如果指定文件是一个已存在的目录或由于其他原因打不开文件会抛出FileNotFoundException他是IOException的一个子类。下面看一个案例:
- OutputStream output = new OutputStream("hello.txt");
- try{
- String data = "hello,123,老马";
- byte[] bytes = data.getBytes(Charset,forName("UTF-8"));
- output.write(bytes);
- }finally{
- output.close();
- }
OutputStream只能一byte或者byte数组写文件,为了写字符串我们调用了String的getBytes() 方法得到他的UTF-8的字节数组,在调用write()方法;
FileInputStream的构造方法:
- public FileInputStream(String name)throws FileNotFoundException;
- public FileInputStream(File file)throws FileNotFoundException;
参数与FileOutputStream类似,可以是文件路径或File对象,但必须是一个已存在的文件,不能是目录,new一个FileInputStream对象,也会实际打开文件,操作系统会分配相关资源,如果文件不存在,会抛出异常FileNotFoundException,如果当前用户没有读的权限就会抛出异常SecurityException;