Java IO流
Java IO流
分类
- 字节流(byte):InputStream,OutputStream
- 字符流(char):Reader,Writer
- 节点流:直接处理数据,例如FileReader、FileOutputStream
- 处理流:对已存在流的连接和封装
节点流(文件流)
字符流
读入
FileReader fr = null
try{
File file = new File("filename");
fr = new FileReader(file);
data = fr.read();
}catch (IOException e){
e.printStackTrace();
}finally{
if(fr != null){
try{
fr.close()
}catch(IOException e){
e.printStackTrace();
}
}
}
注意:
- catch异常,不要用throws
- fanally中close
其他read方法:
- len = read(char[] buff)
写出
File file = new File("filename");//file可以不存在
FileWriter fw = new FileWriter(file, append);//append表示追加或覆盖
fw.write(...);
fw.close();
//try...catch..finally略
- 可以先throws,在用Ctrl+Alt+T快速包围try...catch
字节流
读入
File file = new File("filename");
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[5];
int len;
while((len = fis.read(buffer)) != -1){
...
}
fis.close();
读出
...
byte[] buffer = new byte[5];
int len;
while((len = fis.read(buffer)) != -1){
fos.write(buffer, 0, len);//指定offset和length
}
...
缓冲流
- 作用:提升流的读取、写入的速度
字节流例子
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//1.造文件
File srcFile = new File("filename1");
File destFile = new File("filename2");
//2.造流
//2.1 造节点流
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile);
//2.2 造缓冲流
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//前面几项可合并到一起写
//3.复制的细节:读入、写出
byte[] buffer = new byte[10];
int len;
while ((len = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
//bos.flush();刷新缓冲区
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.资源关闭
//关闭外层流的同时,会自动关闭内层流
if(bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
字符流
可以使用
String data;
While((data = br.readLine()) != null){
//data中不包含换行符,可主动换行
bw.newLine();
}
转换流
提供了字节流和字符流的转换,本身属于字符流
- InputStreamReader:将InputStream转换为Reader
- OutputStreamWriter:将Writer转换为OutputStream
例子
InputStreamReader isr = null;
OutputStreamWriter osw = null;
try {
isr = new InputStreamReader(new FileInputStream("filename1"), "utf-8");
osw = new OutputStreamWriter(new FileOutputStream("filename2"), "gbk");
char[] cbuf = new char[20];
int len;
while((len = isr.read(cbuf)) != -1){
String str = new String(cbuf, 0, len);
System.out.println(str);
osw.write(cbuf, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally...
标准输入输出流
- 对应系统的标准输入输出设备
打印流
- 将基本数据类型转换为字符串输出
- 重定向标准输出流,重载print,输出到文件
数据流
- 操作基本数据类型和String,存到文件里
对象流
- 存储和读取基本数据类型或对象,实现对象的持久化
- 类可序列化要求:
- 类实现Serializable接口
- 提供一个static final常量serialVersionUID
- 类中的所有属性可序列化
随机存取文件流
- 支持随机访问
NIO.2
- Java1.4引入NIO,JAVA7引入NIO.2,支持面向缓冲区的、基于通道的IO操作,更加高效。
分类
- FileChannel:文件
- SocketChannel:TCP客户端
- ServerSocketChannel:TCP服务器端
- DatagramChannel:UDP
File类的补足
- Path:Path path = Paths.get("filename")
- Paths:工具类
- Files:工具类
第三方jar包
- Apache的commence-io包

浙公网安备 33010602011771号