IO流
装饰流(缓冲处理流)
概述
1、Java缓冲流本身并不具有IO流的读取与写入功能,只是在别的流(节点流或其他处理流)上加上缓冲功能提高效率,就像是把别的流包装起来一样,因此缓冲流是一种处理流(包装流)。
2、当对文件或者其他数据源进行频繁的读写操作时,效率比较低,这时如果使用缓冲流就能够更高效的读写信息。
3、因为缓冲流是先将数据缓存起来,然后当缓存区存满后或者手动刷新时再一次性的读取到程序或写入目的地。
特性
1、提高了性能
2、底层还是节点流
3、自动释放底层节点流资源
分类
1、处理字节
2、处理字符
3、打印流
4、数据流和对象流
处理字节
BufferedInputStream:字节缓冲输入流
BufferedOutputStream:字节缓冲输出流
构造方法
//字节缓冲输入流BufferedInputStream(InputStream in)BufferedInputStream(InputStream in, int size)//字节缓冲输出流BufferedOutputStream(OutputStream out)BufferedOutputStream(OutputStream out, int size)
文件拷贝代码示例
/***文件拷贝* 文件的拷贝:字节缓冲输入流+字节缓冲输出流* BufferedInputStream:字节缓冲输入流* BufferedOutputStream:字节缓冲输出流、*/public class Copy_BufferedIntputOutputStream {public static void main(String[] args) {long t1=System.currentTimeMillis();copyFile("G:\\学习相关\\javaweb学习\\jsp视频\\12_EL 表达式 (隐式对象)__rec.avi","C:\\Users\\tfp12\\Desktop\\sp.avi");long t2=System.currentTimeMillis();System.out.println(t2-t1);}public static void copyFile(String srcPath,String destPath){File src=new File(srcPath);File dest=new File(destPath);// InputStream is=null;// OutputStream os=nulltry(InputStream is=new BufferedInputStream(new FileInputStream(src));OutputStream os=new BufferedOutputStream(new FileOutputStream(dest))) {int len=-1;byte[]flush=new byte[1024];while ((len=is.read(flush))!=-1){os.write(flush,0,len);os.flush();}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}
处理字符
BufferedReader:字符输入缓冲流
BufferedWriter:字符输出缓冲流
构造方法(不发生多态)
BufferedReader(Reader in)BufferedReader(Reader in, int sz)
新增方法
readLine():读取一行newLine():换行
示例
/*** 纯文本的拷贝:字符输入缓冲流+字符输出缓冲流* BufferedReader:字符输入缓冲流* BufferedWriter:字符输出缓冲流* 操作单位:字符* 注:只适用于纯文本,是FileReader和FileWriter的装饰流类。* 提高性能*1、readLine():读取一行* 2、newLine():换行*/public class Copy_BufferedReaderWriterStream {public static void main(String[] args) {//创建源和目的地File src=new File("test.txt");File dest=new File("paji1号.txt");//BufferedWriter bw=null;//选择流,不发生多态try(BufferedWriter bw=new BufferedWriter(new FileWriter(dest));BufferedReader br=new BufferedReader(new FileReader(src))) {String line=null;//操作(逐行读取)while ((line=br.readLine())!=null){bw.append(line); //逐行写出bw.newLine(); //换行}} catch (IOException e) {e.printStackTrace();}}}
**InputStreamReader:输入转换流
OutputStreamWrite:输出转换流**
概述
当字节流中都是字符时,转换为字符流效率更高
InputStreamReader:将字节流转换为指定编码的字符流输入
OutputStreamWrite:将字符流转换为指定编码的字节流输出
示例一:控制台输入输出
***转换流:InputStreamReader OutputStreamWrite* 字节流中都是字符时,转换为字符流效率更高* InputStreamReader:将字节流转换为指定编码的字符流输入* OutputStreamWrite:将字符流转换为指定编码的字节流输出* 1、以字符流的形式操作字节流(纯文本的)* 2、指定字符集*/public class InputStreamReader_test {public static void main(String[] args) {test02();}public static void test01() {//System.in为一个字节输入流//System.out为一个字节输出流try(BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(System.out))) {//循环获取键盘的输入String msg="";while (!msg.equals("exit")){msg=reader.readLine(); //循环读取writer.write(msg); //循环写出writer.newLine(); //换行writer.flush(); //强制刷新}} catch (IOException e) {System.out.println("操作异常");}}
示例二:下载网络资源163页面到本地
public static void test02(){//解码//url.openStream()返回一个字节输入流InputStreamtry(BufferedReader reader=new BufferedReader(new InputStreamReader(//下载网络资源new URL("http://www.163.com").openStream(),"GBK"));//编码BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:/Users/tfp12/Desktop/163.html"),"GBK"))){//3、操作(读取)String msg;while ((msg=reader.readLine())!=null){writer.write(msg);writer.newLine();}writer.flush();} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
**PrintStream:打印输入转换流
PrintWriter:打印输出流**
/*** @auther TongFangPing* @date 2019/9/28 23:22.* PrintStream :输出流*/public class PrintStream_study {public static void main(String[] args) throws FileNotFoundException {//输出到控制台java.io.PrintStream ps=System.out;ps.println("扒鸡");ps.println("真好吃!");//true:为自动刷新ps=new java.io.PrintStream(new BufferedOutputStream(new FileOutputStream("paji2.txt")),true);ps.println("德州扒鸡");ps.println("真扒!");ps.close();}}
/*** PrintWriter :输出流* 用法和printStream差不多*/public class PrintWrite_study {public static void main(String[] args) throws FileNotFoundException {PrintWriter pw=new java.io.PrintWriter(new BufferedOutputStream(new FileOutputStream("paji2.txt")),true);pw.println("德州扒鸡");pw.println("真扒呀!");pw.close();}}
**DataStream:数据流
ObjectStream:对象流**
数据流DataStream:读取数据流保持其中的数据类型
1、写出后读取
2、读取顺序与写出顺序保持一致
**DataOutputStream
DataInputStream**
/*** 数据流:读取数据流保持其中的数据类型* 1、先写出后读取* 2、读取顺序与写出顺序保持一致* DataOutputStream* DataInputStream*/public class DataStream {public static void main(String[] args) throws IOException {//写出ByteArrayOutputStream baos=new ByteArrayOutputStream();DataOutputStream dos=new DataOutputStream(baos);//操作数据dos.writeUTF("我爱吃扒鸡");dos.writeInt(18);dos.writeBoolean(true);dos.writeChar('a');dos.flush();byte[]datas=baos.toByteArray();//读取DataInputStream dis=new DataInputStream(new ByteArrayInputStream(datas));//读取顺序保持一致String msg=dis.readUTF();int n=dis.readInt();boolean flag=dis.readBoolean();char ch=dis.readChar();System.out.println(ch);}}
对象流:ObjectStream
ObjectInputStream
ObjectOutputStream
用于存储和读取基本数据类型数据或对象的处理流。它的强大之处在于可以把java中的对象写入到数据源当中,也能把对象从数据源中还原回来。
序列化:用ObjectOutputStream类保存基本数据类型或对象的机制。
反序列化:用ObjectInputStream类读取基本数据类型或对象的机制。
对象的序列化
对象的序列化机制允许把内存中的java对象转换成与平台无关的二进制流,从而允许把这种二进制流持久保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。(序列化过程)当其他程序获取到这种二进制流,就可以恢复成为原来的java对象。(反序列化过程)
序列化的好处在于可将任何实现了Serializable接口的对象转化为字节数据,使其在保存和传输时可被还原。
-序列化是RMI(Remote Method Invoke:远程方法调用)过程的参数和返回值都必须实现的机制,而RMI是JavaEE的基础。因此序列化机制是JavaEE平台的基础。如果需要让某个对象支持序列化机制,则必须让对象所属的类及其属性是可序列化的,为了让某个类是可序列化的,该类必须实现以下两个接口之一。否则,则会抛出NotSerializableException异常
- Serializable
- Externalizable
1、写出后读取
2、读取顺序与写出顺序保持一致
3、不是所有的对象都可以序列化,必须实现接口java.io.Serializable
/*** 序列化(写出)+反序列化(读入)* 对象流:在数据流的基础上添加了Object对象* 1、先写出后读取* 2、读取顺序与写出顺序保持一致* 3、不是所有的对象都可以序列化,必须实现接口java.io.Serializable* ObjectOutputStream* ObjectInputStream*/public class ObjectStream {public static void main(String[] args) throws IOException, ClassNotFoundException {//写出-->序列化(将内存中的对象保存到磁盘中)ObjectOutputStream oos=new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("paji.txt")));//操作数据类型+数据oos.writeUTF("我爱吃扒鸡");oos.writeInt(18);oos.writeBoolean(true);oos.writeChar('a');//对象oos.writeObject("猴赛雷");oos.writeObject(new Date());Employee ep=new Employee("扒鸡",22);oos.writeObject(ep);oos.flush();oos.close();//读取--->反序列化(从磁盘中读取数据进行还原成对象)ObjectInputStream ois=new ObjectInputStream(new BufferedInputStream(new FileInputStream("paji.txt")));//读取顺序保持一致String msg=ois.readUTF();int n=ois.readInt();boolean flag=ois.readBoolean();char ch=ois.readChar();//对象的数据还原Object str=ois.readObject();Object date=ois.readObject();Object employee=ois.readObject();if(str instanceof String){String strObj=(String)str;System.out.println(strObj);}if(date instanceof Date){Date dateObj=(Date)date;System.out.println(date);}if(employee instanceof Employee){Employee employeeObj=(Employee)employee;System.out.println(employeeObj);}ois.close();}static class Employee implements java.io.Serializable{private String name;private int age;public Employee(String name, int age) {this.name = name;this.age = age;}public void setAge(int age) {this.age = age;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public String getName() {return name;}}}
文件的切割读写(一)
/*** 文件切割读写* 随机读取和写入流:RandomAccessFile*/public class RandomAccessFile_study {public static void main(String[] args) throws IOException {//文件可以分为多少块File src=new File("randomAccess_study.iml");//文件的总长度long len=src.length();//设置每块大小int blockSize=100;//块数:不够一块,按一块处理int blockNumber=(int)Math.ceil(len*1.0/blockSize);System.out.println("文件总长度:"+len+"字节,可以分为:"+blockNumber+"块");int beginPos=0;//如果一块的大小不够实际需要的大小,则去一块的大小,否则取实际大小int actualSize=(int)(blockSize>len?len:blockSize);//分块读取for(int i=0;i<blockNumber;i++){beginPos=i*blockSize;if(i==blockNumber-1){ //最后一块actualSize=(int)len;}else{actualSize=blockSize;len-=actualSize; //剩余量}System.out.println(i+"-->"+beginPos+"-->"+actualSize);split(i,beginPos,actualSize);}}//分开思想,起始、实际大小/*** 分段读取* 指定第i块的起始位置和实际长度* @param i* @param beginPos* @param actualSize* @throws IOException*/public static void split(int i,int beginPos,int actualSize) throws IOException {RandomAccessFile raf=new RandomAccessFile(new File("randomAccess_study.iml"),"r");//随机读写raf.seek(beginPos);byte[]flush=new byte[1024];int len=-1;while ((len=raf.read(flush))!=-1){if(actualSize>len){ //获取本次读取的所有内容System.out.println(new String(flush,0,len));actualSize-=len;}else{System.out.println(new String(flush,0,actualSize));break;}}}public static void Test01() throws IOException {//随机读写流,第一个参数:文件路径 第二个参数,模式:r、rw、rws、rwdRandomAccessFile raf=new RandomAccessFile(new File("randomAccess_study.iml"),"r");//设置操作(读写)文件的指针位置raf.seek(2);//读取byte[]flush=new byte[1024];int len=-1;while ((len=raf.read(flush))!=-1){System.out.println(new String(flush,0,len));}}}
文件的切割读写(二)
* 文件切割读写* 随机读取和写入流:RandomAccessFile*/public class RandomAccessFile_study02 {public static void main(String[] args) throws IOException {//文件可以分为多少块File src=new File("io.png");//文件的总长度long len=src.length();//设置每块大小int blockSize=1024;//块数:不够一块,按一块处理int blockNumber=(int)Math.ceil(len*1.0/blockSize);System.out.println("文件总长度:"+len+"字节,可以分为:"+blockNumber+"块");int beginPos=0;//如果一块的大小不够实际需要的大小,则去一块的大小,否则取实际大小int actualSize=(int)(blockSize>len?len:blockSize);//分块读取for(int i=0;i<blockNumber;i++){beginPos=i*blockSize;if(i==blockNumber-1){ //最后一块actualSize=(int)len;}else{actualSize=blockSize;len-=actualSize; //剩余量}System.out.println(i+"-->"+beginPos+"-->"+actualSize);split(i,beginPos,actualSize);}}//分开思想,起始、实际大小/*** 分段读取* 指定第i块的起始位置和实际长度* @param i* @param beginPos* @param actualSize* @throws IOException*/public static void split(int i,int beginPos,int actualSize) throws IOException {RandomAccessFile raf=new RandomAccessFile(new File("io.png"),"r");RandomAccessFile raf2=new RandomAccessFile(new File("dest/"+i+"io.png"),"rw");//随机读写raf.seek(beginPos);byte[]flush=new byte[1024];int len=-1;while ((len=raf.read(flush))!=-1){if(actualSize>len){ //获取本次读取的所有内容raf2.write(flush,0,len);actualSize-=len;}else{raf2.write(flush,0,actualSize);break;}}}public static void Test01() throws IOException {//随机读写流,第一个参数:文件路径 第二个参数,模式:r、rw、rws、rwdRandomAccessFile raf=new RandomAccessFile(new File("randomAccess_study.iml"),"r");//设置操作(读写)文件的指针位置raf.seek(2);//读取byte[]flush=new byte[1024];int len=-1;while ((len=raf.read(flush))!=-1){System.out.println(new String(flush,0,len));}}}
文件的切割与合并Demo
/*** 面向对象封装文件分割与合并* 文件切割读写**/public class SplitFile {//源头private File src;//目的地(文件夹)private String desDir;//所有分割后的文件存储路径private List<String> desPaths;//每块大小private int blockSize;//块数private int size;/***构造方法* @param srcPath:文件源* @param desDir:目的地路径* @param blockSize:每个文件大小*/public SplitFile(String srcPath, String desDir, int blockSize) {this.src = new File(srcPath);this.desDir = desDir;this.blockSize = blockSize;this.desPaths=new ArrayList<String>();//初始化init();}//初始化private void init(){//文件的总长度long len=this.src.length();//块数:不够一块,按一块处理this.size=(int)Math.ceil(len*1.0/blockSize);//路径for(int i=0;i<size;i++){this.desPaths.add(this.desDir+"/"+i+"-"+this.src.getName());}}/*** 分割* 1、计算每一块的起始大小* 2、分割*/public void split() throws IOException {//文件的总长度long len=src.length();int beginPos=0;//如果一块的大小不够实际需要的大小,则去一块的大小,否则取实际大小int actualSize=(int)(blockSize>len?len:blockSize);//分块读取for(int i=0;i<size;i++) {beginPos = i * blockSize;if (i == size - 1) { //最后一块actualSize = (int) len;} else {actualSize = blockSize;len -= actualSize; //剩余量}splitDetail(i,beginPos,actualSize);}}//分开思想,起始、实际大小/*** 分段读取* 指定第i块的起始位置和实际长度* @param i* @param beginPos* @param actualSize* @throws IOException*/public void splitDetail(int i,int beginPos,int actualSize) throws IOException {RandomAccessFile raf=new RandomAccessFile(this.src,"r");RandomAccessFile raf2=new RandomAccessFile(this.desPaths.get(i),"rw");//随机读写raf.seek(beginPos);byte[]flush=new byte[1024];int len=-1;while ((len=raf.read(flush))!=-1){if(actualSize>len){ //获取本次读取的所有内容raf2.write(flush,0,len);actualSize-=len;}else{raf2.write(flush,0,actualSize);break;}}raf2.close();raf.close();}public void merge(String destPath) throws IOException {//输出流(文件追加的方式)OutputStream os=new BufferedOutputStream(new FileOutputStream(destPath,true));//输入流for(int i=0;i<desPaths.size();i++){InputStream is=new BufferedInputStream(new FileInputStream(desPaths.get(i)));//拷贝byte[]flush=new byte[1024];int len=-1;while ((len=is.read(flush))!=-1){os.write(flush,0,len);}os.flush();is.close();}os.close();}public static void main(String[] args) throws IOException {SplitFile sf=new SplitFile("E:/idea/randomAccess_study/src/randomaccess_study/SplitFile.java","dest",1024);sf.split();sf.merge("合并Test.java");}}
