定义:io流简单的来说就是输入和输出流,io流用来处理设备间的数据传输。
按操作数据分为:字节流和字符流
按流向分为:输入流和输出流
字节流是java中可以按照最小字节单位读取的流,每次读写一个字节
字符流是基于字节流,去查找指定的码表
如果是纯文本数据优先使用字符流,除此之外都是使用字节流
io流的整体架构图:
io流使用的简单示例:
字节流读写操作
/**
* 读写文件流操作 字节流
* @param url
* @throws IOException
*/
public static void writeFile(String url,String newUrl){
File file = new File(url);
File newFile = new File(newUrl);
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(file);
fileOutputStream = new FileOutputStream(newFile);
byte[] bt = new byte[64];
int length;
while ((length = fileInputStream.read(bt)) != -1){
fileOutputStream.write(bt,0,length);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fileOutputStream.close();
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 读写文件操作 字符流
* @param url
* @param newUrl
*/
public static void writeTextFile(String url,String newUrl){
File file = new File(url);
File newFile = new File(newUrl);
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
try {
bufferedReader = new BufferedReader(new FileReader(file));
bufferedWriter = new BufferedWriter(new FileWriter(newFile));
String str;
while ((str = bufferedReader.readLine()) != null){
bufferedWriter.write(str+"\n");
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bufferedWriter.close();
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
java io流面试相关
什么是缓冲区?有什么作用?
缓冲区就是一个特殊的内存区域,为了提升性能将一部分数据读写到缓存区,缓冲区满了会被动写入或者写出,缓冲区也可以可以强制刷新的flush()方法。字符流都是基于缓冲区操作。
BufferedReader属于那种流,它的作用是什么,有哪些经典方法?
属于字符流,有readLine()方法,可以用来读取一行
字节流和字符流转换?
InputStreamReader、OutputStreamReader
InputStream里的read()返回的是什么,read(byte[] data)返回的是什么?
返回int类型(范围0-255)
read()将读取的字节存储在这个数组中,返回传入的这个数组
OutputStream里的write()是什么,write(byte[] b,int off,int len)这个方法三个参数是什么?
write()将指定字节写入,byte数组,传入的第一个字符,len实际长度
什么是java序列化,如何实现序列化?
序列化就是一种用来处理对象流的机制,将对象的内容进行流化,可以将流化后的对象进行读写操作,也可以用于网络传输,序列化是为了解决在对象读写操作时所引发的问题。
需要被序列化的类继承Serialize接口,然后使用一个输出流(FileOutputStream)来构建一个输出流,在使用ObjectOutputStream对象的write()方法对对象序列化
/**
* 序列化
* @param object
* @return
*/
public static byte[] SerializeObject(Object object){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(object);
return byteArrayOutputStream.toByteArray();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 反序列化
* @param bytes
* @return
*/
public static Object UnSerializeObject(byte[] bytes){
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
try {
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
return objectInputStream.readObject();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}