Day16 IO流

时间:2023-03-09 05:12:18
Day16 IO流

流的概念和作用

流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象。即数据在两设备间的传输称为流,流的本质是数据传输,根据数据传输特性将流抽象为各种类,方便更直观的进行数据操作。

Java流类图结构:

Day16 IO流

Stream流的聚合操作

1.末端方法;都是一次性的使用,流就会关闭,不能再用此流了。

2.中间方法;会返回一个新的流对象,继续调用其他的聚合方法操作。

 public class TestStream1 {

     public static void main(String[] args) {
//存整数 生产者模式 思想
//返回 一个 流对象
IntStream stream = IntStream.builder().add().add().add().add().build();
// System.out.println(stream.max().getAsInt());//末端
// IntStream stream1 = IntStream.builder().add(11).add(22).add(33).add(44).build();
// System.out.println(stream1.min().getAsInt());
// System.out.println(stream.min().getAsInt());
// System.out.println(stream.sum());
// System.out.println(stream.average().getAsDouble());
// System.out.println(stream.count());
//是否 所有的 数据 都 满足条件,都满足 true,否则不成立
/* System.out.println(stream.allMatch(new IntPredicate() { @Override
public boolean test(int value) {
// TODO Auto-generated method stub
return value > 10;
}
}));*/
// System.out.println(stream.allMatch(v-> v > 10));
//只要有一个元素满足条件 就 成立 true
// System.out.println(stream.anyMatch(v-> v > 22));
//中间方法
// System.out.println(stream.filter(v-> v > 22).count());
stream.filter(v->v>).forEach(System.out::println); } }

IO流

File类

File类主要用来获取文件(或目录)本身的一些信息,如文件的名字,不涉及文件的读写操作。

常用方法

对文件的操作

 public class TestFile {

     public static void main(String[] args) throws IOException {
// File
//文件 :
File f1 = new File("d:/data");
File f = new File(f1,"x.txt");
// File f = new File("d:/data","x.txt");
// File f = new File("d:\\data\\x.txt");
// File f = new File("./x.txt");
System.out.println(f.exists());
//新建文件
f.createNewFile();//
//判断文件是否存在
System.out.println(f.exists());
//文件名字
System.out.println(f.getName());
//文件的路径:根据指定的 文件路径不同显示不同,可以显示 绝对的也可以显示相对的
System.out.println(f.getPath());
//绝对路径
System.out.println(f.getAbsolutePath());
//父路径
System.out.println(f.getParent());
//文件 是否 可读,可写
System.out.println(f.canRead());
System.out.println(f.canWrite());
//判断 是否是文件
System.out.println(f.isFile());
//最后修改的时间
long time = f.lastModified();
System.out.println(time);
//格式化
//DateFormat -> SimpleDateFormat
System.out.println(DateFormat.getDateInstance().format(time));
//文件的长度:文件内容的字节数
long len = f.length();//
System.out.println(len);
//删除文件
f.delete();
System.out.println(f.exists()); } }

对目录的操作

 public class TestFile1 {

     public static void main(String[] args) {
// File目录
File f = new File("d:/data");
// File f = new File("d:/data2/data3");
System.out.println(f.exists());
//是否 是目录
System.out.println(f.isDirectory());
//建立目录
// f.mkdir();
//建立目录 包括 父目录
// f.mkdirs();
//获得 目录下 的 子目录 和文件的 名称 的数组
String [] str1 = f.list();
Arrays.stream(str1).forEach(System.out::println);
//FilenameFilter文件名过滤器
String [] str2 = f.list(new FilenameFilter() { @Override
public boolean accept(File dir, String name) {
// 把扩展名 是 java的过滤出来
return name.endsWith("java");
}
});
String [] str3 = f.list((d,name)->name.endsWith("java")); System.out.println("------------------------");
Arrays.stream(str2).forEach(System.out::println);
System.out.println("------------------------");
//-----------------------------------------------------
File[] fl1 = f.listFiles();
for(File ff:fl1) {
if(ff.isFile()) {
System.out.println(ff.getName());
}else {
System.out.println(ff.getPath());
}
}
//FileFilter过滤器
File[] fl2 = f.listFiles(new FileFilter() { @Override
public boolean accept(File pathname) {
//把扩展名 是 java的过滤出来
return pathname.getName().endsWith("java");
}
});
System.out.println("------------------------");
for(File ff:fl2) {
if(ff.isFile()) {
System.out.println(ff.getName());
}else {
System.out.println(ff.getPath());
}
}
} }

流的分类

序列化是写,反序列化是读

按照流的数据类型:分为字节流和字符流

按照方向:输入和输出

按照功能:节点流和处理流

节点流:直接对数据源(文件)操作。

处理流(过滤流,包装流):套接(包装)在节点流之上的,提供更丰富的功能或提高效率。

字节流

字节流由2个抽象类定义:

InputStream:所有字节输入流的父类

int read():从输入流中读取一个字节,到达文件尾返回-1

void close():关闭此输入流并释放与该留关联的所有系统资源

OutputStream:所有字节输出流的父类

abstract void write(int):将指定的字节写入此输出流

void close():关闭此输出流并释放与该留关联的所有系统资源

文件流

FileInputStream

read():读一字节,到文件末尾返回-1

read(byte[]): 返回读到的字节数

read(,,) :(存入的字节数组,存入的起始位置,存入几个字节)

public static void main(String[] args) throws IOException {
// FileInputStream 文件 输入流
//1 创建流对象
File f = new File("d:/data/a.txt");
FileInputStream fin = new FileInputStream(f);
//把字节流转换成字符流
//转换字符流
// InputStreamReader ir = new InputStreamReader(fin);
//2读
/* int temp ;
while((temp = fin.read())!= -1) {
System.out.print((char)temp);
}*/
// byte [] b = new byte[(int)f.length()];
byte [] b = new byte[fin.available()];//获得流中的字节数
//把文件的内容 读入 到 b中
// fin.read(b);
// (存入的字节数组,存入的起始位置,存入几个字节)
fin.read(b, , );// ab
String s = new String(b,"gbk");
System.out.println(s);
//3.关
fin.close();
/*ir.close();*/
// ir.close();
}

FileOutputStream

write(int ):写一字节

write(byte[]):写一个字节数组

write(b, 2, 2):(数组,起始位置,字节数)

public static void main(String[] args) throws IOException {
// FileOutputStream 写 输出
//String s = "hello"存到 d:/data/b.txt
//1 true追加 ,false覆盖 吗,默认 false
FileOutputStream fout = new FileOutputStream("d:/data/b.txt",false);
//2写
String s = "hello";
byte [] b = s.getBytes();
// fout.write(b[0]);//写一字节
// fout.write(b);//写一个字节数组 ,
// (数组,起始位置,字节数)
fout.write(b, , );
//3.关
fout.close();
}

缓冲流

BufferedInputStream和BufferedOutputStream,默认8192字节,提供了缓冲区,提高效率

public class TestFileInputOutputStream {

    public static void main(String[] args)  {
// 复制图片
/* //1 。创建对象
FileInputStream fin = new FileInputStream("d:/data/aoteman.jpg");
FileOutputStream fout = new FileOutputStream("d:/data/aotemannew.jpg"); BufferedInputStream bfin = new BufferedInputStream(fin);//缓冲流 提供了 板车 8192字节
BufferedOutputStream bfout = new BufferedOutputStream(fout);// 提供了汽车 8192字节
//2读和写
int temp;
while((temp = bfin.read())!=-1) {
bfout.write(temp);
}
bfout.flush();//强制写入
//3
bfin.close();
bfout.close();*/ //----------------------------------------------------
FileInputStream fin = null;
FileOutputStream fout = null;
BufferedInputStream bfin = null;
BufferedOutputStream bfout = null;
try {
fin = new FileInputStream("d:/data/aoteman.jpg");
fout = new FileOutputStream("d:/data/aotemannew.jpg");
bfin = new BufferedInputStream(fin);//缓冲流 提供了 板车 8192字节
bfout = new BufferedOutputStream(fout);// 提供了汽车 8192字节
int temp;
while((temp = bfin.read())!=-) {
bfout.write(temp);
}
bfout.flush();//强制写入
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(bfin != null) {
bfin.close();
}
if(bfout != null) {
bfout.close();
}
} catch (IOException e) {
e.printStackTrace();
} } } }

数据流

DataInputStream和DataOutputStream

提供了 使用 Java的不同数据类型 的方式 读和写。

public class TestDateOutputStream {

    public static void main(String[] args) throws Exception {
// DataOutputStream数据流
//-------------写--------------------------
//1
// DataOutputStream dout = new DataOutputStream(new FileOutputStream("d:/data/stu.txt"));
FileOutputStream fout = new FileOutputStream("d:/data/stu.txt");
DataOutputStream dout = new DataOutputStream(fout);
//2.写
int [] no = {,,};
String [] name = {"aa","bb","cc"};
for(int i = ; i < no.length; i++) {
dout.writeInt(no[i]);
dout.writeUTF(name[i]);
}
//3.
dout.close();
//---------------读-------------------------
FileInputStream fin = new FileInputStream("d:/data/stu.txt");
DataInputStream din = new DataInputStream(fin);
for(int i = ; i < no.length; i++) {
System.out.println(din.readInt());
System.out.println(din.readUTF());
}
din.close();
} }

对象流

ObjectInputStream和ObjectOutputStream

永久性的存储对象,需要实现Serializable接口

序列化:把对象以二进制的形式存储起来。

反序列化:把对象以二进制流的形式从文件中还原

 import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable; class Student implements Serializable{ /**
* 字节码文件中存储的那个版本号, 不显示指定,系统会自动随机一个
*/
private static final long serialVersionUID = 1L;
private int no;
private String name;
private int age;
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} }
public class TestObjectStream {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
// 创建对象
Student guojing = new Student();
guojing.setNo();
guojing.setName("郭靖");
//序列化 把对象 以二进制流 的形式存储起来。-------------------------------------------------------
//
/*// ObjectOutputStream obj = new ObjectOutputStream(new FileOutputStream("d:/data/obj.txt"));
FileOutputStream fout = new FileOutputStream("d:/data/obj.txt");
ObjectOutputStream obj = new ObjectOutputStream(fout);
//2写
obj.writeObject(guojing);
//3.
obj.close();*/
//反序列化 把对象 以二进制流的形式 从文件中还原-----------------------------------------------------
//
FileInputStream fin = new FileInputStream("d:/data/obj.txt");
ObjectInputStream objin = new ObjectInputStream(fin);
//2读
Student stu = (Student)objin.readObject();
System.out.println(stu.getNo()+","+stu.getName());
//3.
objin.close(); } }

打印输出字节流

PrintStream

 public class TestPrintStream {

     public static void main(String[] args) throws IOException {
/*// TODO Auto-generated method stub
System.out.println("hello");
System.err.println("abc");*/
//PrintStream
//把读到的文件 的内容 在控制台上打印输出
//System.out
//
FileInputStream fin = new FileInputStream("d:/data/a.txt");
//2读
byte [] b = new byte[fin.available()];
fin.read(b);
//3.
fin.close();
//-----------------打印到控制台------------------------------
//System.out控制台输出 System.in控制台输入
PrintStream print = new PrintStream(System.out);
print.println(new String(b,"gbk"));
print.close();
} }

字符流

抽象父类
Reader
Writer

子类:

1.文件字符流(节点流)

FileReader
FileWriter

 public class TestReader1 {

     public static void main(String[] args) throws IOException {
// 逆序写入
//读-----------------------------
File f = new File("d:/data/a.txt");
FileReader fr = new FileReader(f);
int temp;
StringBuffer sf = new StringBuffer();
while((temp = fr.read())!= -) {
sf.append((char)temp);//连接
}
fr.close();
//写------------------------------
FileWriter fw = new FileWriter("d:/data/b.txt");
//反转
String s = sf.reverse().toString();
fw.write(s);//写入
fw.close();
} }

2.字符缓冲流

BufferedReader
BufferedWriter

 public class TestReader {

     public static void main(String[] args) throws IOException {
// FileReader------------读-------------------------
//
FileReader fr = new FileReader("d:/data/a.txt");
BufferedReader bfr = new BufferedReader(fr);
//2读
String s = null;
while((s = bfr.readLine())!= null) {
System.out.println(s);
} /*int temp ;
while((temp = fr.read())!= -1) {
System.out.print((char)temp);
}*/
//3.
fr.close();
//FileWriter---------------写----------------------------
/* FileWriter fw = new FileWriter("d:/data/b.txt");
String s = "hello";
fw.write(s);
fw.close();*/ } }

3.打印输出流

PrintWriter

 import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter; public class TestPrintWriter { public static void main(String[] args) {
// PrintWriter
/* PrintWriter pw = new PrintWriter("d:/data/num.txt");
for(int i = 1; i <= 10; i++) {
// System.out.println(i);
pw.println("数字:"+i);
}
pw.close();*/
//----------------循环写入内容------------------------
//1
// System.in
/* BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter("d:/data/namenew.txt");
String s;
while(true) {
s = br.readLine();//读一行
if(s.equals("q")) {
break;
}
pw.println(s);
}
br.close();
pw.close();
*/
//自动资源释放
try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter("d:/data/namenew.txt");){ String s;
while(true) {
s = br.readLine();//读一行
if(s.equals("q")) {
break;
}
pw.println(s);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} }