java面试总结(3)之IO

图片来源

1.字节流和字符流的区别

字节流是jdk1.0引入的,字符流是jdk1.1引入的,字节流操作二进制数据,字符流只能操作字符文本类数据,通常情况多使用字节流更高效,如果字符文本中有汉字最好使用字符流避免乱码

2.System.out.println()用到了什么流

System类中有一个PrintStream类型的静态常量,和PrintWriter打印流一样,out是该对象的引用名称,该对象提供了一个println方法用于打印字符

3.Filter流

FilterInputStream,FilterOutputStream本身并没有提供什么新的方法不常用

FilterReader,FilterWriter是模板类用于定义一组规范,由我们自行扩展

4.SequenceInputStream的作用

可以把两个或多个输入流头尾相连,例如把两个文件的内容拷贝到一个文件中,可以用

new SequenceInputStream(in1,in2);

5.管道流概述

管道流的种类:PipedInputStream,PipedOutputStream,PipedReader,PipedWriter

作用:多线程间操作流使用该对象

注意点:不要在同一个线程中同时使用管道输入、输出流,会造成死锁

               可以一个线程读,一个线程写。

使用:两个对象任意调用connect传入对方即可连接,例如 new PipedInputStream.connect(new PipedOutputStream());

6.IO流关闭顺序

如果使用多层包装流,则只关闭最外层的流即可

输入流和输出流在finally中,先关闭输入流在关闭输出流,比反过来稍微好一点,原因:有可能输出的关闭的过程中可能还在输入,但是通常都是在输入流的内容完全输出后,才关闭,因此也可以说在finally中无所谓关闭顺序

7.序列化反序列化

序列化是指将java对象以流的形式传入到网络中或磁盘中

反序列化是指将网络或磁盘中的流转化为java对象

使用序列化的对象的类必须实现Serializable接口

每个实现了序列化接口的对象都有一个serialVersionUID且是唯一的,序列化和反序列化对象时需要该属性保持一致

transient关键字声明的属性不会被序列化

序列化对象new ObjectOutputStream(new FileInputStream("in"))的writeObject(Object o);

反序列化对象new ObjectInputStream(new FileOutputStream("out"))的readObject();

8.手写字节流字符流copy代码

字节流:

public static void main(String[] args){
    FileInputStream in = null;
    FileOutputStream out = null;

    try{
        in = new FileInputStream(new File("in"));
        out = new FileOutputStream(new File("out"));
        byte[] b = new byte[1024];
        int len;
        while((len = in.read(b)) != -1){
            out.write(b,0,len);
        }
    }catch(Exception e){
        e.printStackTrace();        
    }finally{
        try{
            in.close();
            out.close();
        }catch(Exception e){
            e.printStackTrace();        
        }
    }
}

字符流:

public static void main(String[] args) {
        BufferedReader in = null;
	BufferedWriter out = null;
	try{
		in = new BufferedReader(new FileReader("in"));
		out = new BufferedWriter(new FileWriter("out"));			
		String line = "";			
		while((line = in.readLine()) != ""){
			out.write(line);
		}
	}catch (Exception e) {
			e.printStackTrace();
	}finally{
		try {
			in.close();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}			
	}
}

猜你喜欢

转载自blog.csdn.net/m0_37414960/article/details/81358157