字节流
FileInputStream(文件字节输入流)
作用:
以内存为基准,可以把磁盘文件中的数据以字节的形式读入到内存中去。
每次读取一个字节
构造器 | 说明 |
public FileInputStream(File file) | 创建字节输入流管道与源文件接通 |
public FileInputStream(String pathname) | 创建字节输入流管道与源文件接通 |
方法名称 | 说明 |
public int read() | 每次读取一个字节返回,如果发现没有数据可读会返回-1. |
public int read(byte[] buffer) | 每次用一个字节数组去读取数据,返回字节数组读取了多少个字节,如果发现没有数据可读会返回-1. |
注意事项:
使用FileInputStream每次读取一个字节,读取性能较差,并且读取汉字输出会乱码。
每次读取多个字节
注意事项:
使用FileInputStream每次读取多个字节,读取性能得到了提升,但读取汉字输出还是会乱码。
使用字节流读取中文,如何保证输出不乱码,怎么解决?
定义一个与文件一样大的字节数组,一次性读取完文件的全部字节。
一次读完全部字节
方式一:
自己定义一个字节数组与被读取的文件大小一样大,然后使用该字节数组,一次读完文件的全部字节。
方法名称 | 说明 |
public int read(byte[] buffer) | 每次用一个字节数组去读取,返回字节数组读取了多少个字节,如果发现没有数据可读会返回-1. |
方式二:
Java官方为InputStream提供了如下方法,可以直接把文件的全部字节读取到一个字节数组中返回。
方法名称 | 说明 |
public byte[] readAllBytes() throws IOException | 直接将当前字节输入流对应的文件对象的字节数据装到一个字节数组返回 |
写字节出去
构造器 | 说明 |
public FileOutputStream(File file) | 创建字节输出流管道与源文件对象接通 |
public FileOutputStream(String filepath) | 创建字节输出流管道与源文件路径接通 |
public FileOutputStream(File file,boolean append) | 创建字节输出流管道与源文件对象接通,可追加数据 |
public FileOutputStream(String filepath,boolean append) | 创建字节输出流管道与源文件路径接通,可追加数据 |
方法名称 | 说明 |
public void write(int a) | 写一个字节出去 |
public void write(byte[] buffer) | 写一个字节数组出去 |
public void write(byte[] buffer , int pos , int len) | 写一个字节数组的一部分出去。 |
public void close() throws IOException | 关闭流。 |
释放资源的方式
try-catch-finally
try{
...
...
} catch (IOException e){
e.printStackTrace();
}finally{
}
finally代码区的特点:
无论try中的程序是正常执行了,还是出现了异常,最后一定会执行finally区,除非JVM终止。
作用:
一般用于在程序执行完成后进行资源的释放操作(专业及做法)。
try-with-resource
InputStream is = null;
OutputStream os = null;
try{
...
}catch(Exception e){
e.printStackTrace();
}finally{
//关闭资源!
try{
if(os != null)os.close();
}catch(Exception e){
e.printStackTrace();
}
try{
if(is != null)is.close();
}catch(Exception e){
e.printStackTrace();
}
}
使用try-catch-finally方式释放资源容易导致代码臃肿,不优雅。
try(定义资源1;定义资源2;...){
可能出现异常的代码;
}catch(异常类名 变量名){
异常的处理代码:
}
public abstract class InputStream implements Closeable{ }
public abstract class OutputStream implements Closeable, Flushable { }
public interface Closeable extends AutoCloseable { }
注意:
该资源使用完毕后,会自动调用其close()方法,完成对资源的释放!
()中只能放置资源,否则报错
资源一般指的是最终实现了AutoCloseable接口。