java IO 字节流(一)FileInputStream与FileOutputStream
与字符流不同,字节流可以处理任意类型的文件,其实从类的命名就可以很容易的区分哪些类是操作字节流或者哪些类是操作字符流的,字节流的都是以Stream结尾的,而操作字符流的类都是以Reader或Writer结尾的。
字节流根据流向不同也可以分为两类:
1.输入流
以InputStream为父类的一系列操作字节流的类,相对于内存而言,是将流读取到内存中,所以是输入流。
2.输出流
以OutputStream为父类的一系列操作字节流的类,相对于的内存而言,是将内存中的流输出到文件,所以为输出流。
本篇主要总结一下FileInputStream与FileOutputStream
1.FileInputStream
主要用来读取非文本数据的文件,从源码中可以知道构造方法有三种,常用的有两种,并且这两种可以算是一种,因为传的如果是路径,源码中也会直接new一个File
注意:用字节流读取中文显示到控制台会出现乱码情况,是因为汉子占两个字节,而字节流每次只能读取一个字节,就把它转为字符,写入文本时不会出现这种情况
读取时常用的有三种方式:
1.每次读取一个byte数组,效率高(查看源码也是一次读取一个字节,存到byte数组中)
2.每次读取一个字节,效率低(一般说的低是指读取一个写入一个,效率肯定会慢)
3.创建的byte数组与流大小相等,使用于较小的文件,不推荐使用,如果文件过大会导致byte数组创建失败。
最后一定要关闭流
注:
选用文本时因为可以在控制台打印,其他的不能只管的在控制台查看,但是话说回来,输入流都是为输出流做准备的,没有说在程序中打印某一部分流的,一般都是用来上传下载,或者复制文件
2.FileOutputStream
FileOutputStream一般是与FileInputStream成对使用的,构造方法有五种,常用的有两种,两种可以做了解(多一个是否追加的参数,布尔值,默认FALSE),常用的两种构造方法与FileInputStream一致。
public FileOutputStream(String name) throws FileNotFoundException {
this(name != null ? new File(name) : null, false);
}
public FileOutputStream(String name, boolean append)
throws FileNotFoundException
{
this(name != null ? new File(name) : null, append);
}
public FileOutputStream(File file) throws FileNotFoundException {
this(file, false);
}
public FileOutputStream(File file, boolean append)
throws FileNotFoundException
{
String name = (file != null ? file.getPath() : null);
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(name);
}
if (name == null) {
throw new NullPointerException();
}
if (file.isInvalid()) {
throw new FileNotFoundException("Invalid file path");
}
this.fd = new FileDescriptor();
fd.attach(this);
this.append = append;
this.path = name;
open(name, append);
}
public FileOutputStream(FileDescriptor fdObj) {
SecurityManager security = System.getSecurityManager();
if (fdObj == null) {
throw new NullPointerException();
}
if (security != null) {
security.checkWrite(fdObj);
}
this.fd = fdObj;
this.append = false;
this.path = null;
fd.attach(this);
}
主要用来将流输出,常用write方法,可以将单个字节作为参数,也可以将byte数组作为参数,byte数组作为参数也是循环写字节
组合使用如下:
当然可以使用byte数组作为参数,也可以是图片,视频等各种文件,需要注意的是最后一定要将流关闭。