首页 > 技术文章 > I/O流

hcjk12580 2019-12-12 20:58 原文

 

总结

I/O流

File类

在java.io包下

File file = new File("路径")

file.exists(),判断文件是否存在

file.createNemFile();创建文件

file.delete;删除文件

file.isDirectory();判断是否是文件夹

file.list();把文件夹中里的文件名转化String数组

流的分类

1.按方向分类:输入流,输出流

2.按类型分类:字节流,字符流

3.按操作方式:节点流,过滤流

4.转换流

字节流

FileInputSteam :输入流

read()方法:读取一个字节,并以整数的形式返回(0-255),如果返回-1,表示读取到末尾

read(byte b[])方法:读取的是一系列字节,并且存储到一个byte类型的数组中,这个数组相等与一个缓存区,返回的是当前读取道德字节数,如果读到文件末尾返回-1.

//读文件
FileInputStream fis = null;
try {
fis = new FileInputStream("Test.txt");

byte[] bytes = new byte[12];
String str = null;

int n = 0;

while((n=fis.read(bytes)) != -1){
str = new String(bytes,0,n);
System.out.println(str);
}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(fis != null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}

FileOutputSteam :输出流

write(byte[] b)方法:将b.length个字节,从指定byte数组写入文件中.

FileOutputStream("地址",true),在输出的时候就不会覆盖原来的内容,而是在后面追加.

FileOutputStream fos = null;
try {
fos = new FileOutputStream("c:\\test\\TestWrite.txt");

//fos.write(97);
//fos.write(98);
//fos.write(99);
//fos.write(100);

String str = "sdfdgfdgffd";
//getBytes()方法返回的是一个byte数组
fos.write(str.getBytes());


try {
Thread.sleep(30000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if(fos != null) {
fos.close();
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

字节流比较适用于 图片视频等文件使用

字符流

Reader 输入流的抽象类

Writer 输出流的抽象类

两个流与字节流的很像,只是字符流输入输出的单位是一个字符,这样读取像中文是就不会乱码.

//Reader 字符流读 抽象类
//Writer 字符流写 抽象类
Reader r = null;
Writer w = null;
try {
r = new FileReader("Test.txt");

w = new FileWriter("Test1.txt");

char [] cs = new char[1024];
int index = 0;

while((index = r.read(cs)) != -1){
String str = new String(cs,0,index);
System.out.println(str);

w.write(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(r != null){
r.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(w != null){
w.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
缓冲流

缓存流 也叫 过滤流 或 处理流

字节缓冲流

BufferedInputStream 输入缓冲流

BufferedOutputStream 输出缓冲流 ---flush()方法用于疏通管道,但是关闭输出时,自动调用该方法

字符缓冲流

BufferedReader 输入缓冲流 -----readlne()方法按行读取

BufferedWriter 输出缓冲流 ----打印时不会自动换行,需要手动换行

打印流 用于字符输出流

PrintWriter类

println();方法 自动换行

转换流

InputStreamReader 将字节流转换为字符流

OutStreamWriter 将字符流转换为字节流

处理流

对象流

ObjectOutputStream 对象输出流

ObjectInputStream 对象输入流

使用对象流,对象的封装类必须实现Serializable接口

 

推荐阅读