流的概念
概念:内存与存储设备之间传输数据的通道
流的分类
- 按方向(重点)
- 输入流:将存储设备中的 内容读入到内存中
- 输出流:将内存中的内容写入到存储设备中
- 按单位
- 字节流:以字节为单位,可以读写所有数据
- 字符流:以字符为单位,只能读写文本数据
- 按功能
- 节点流:具有实际传输数据的读写功能
- 过滤流:在节点流的基础之上增强功能
字节流
-
字节流的父类(抽象类)
InputStream:字节输入流
OutputStream:字节输出流
-
字节流的实现类
- FileInputStream
package study; import java.io.FileInputStream; public class Demo { public static void main(String[] args) throws Exception { FileInputStream fis = new FileInputStream("d:\\Study.txt"); byte[] buf = new byte[3]; int count=0; //read(byte[] a)从该输入流读取最多 b.length个字节的数据存入a数组。 // 返回实际读到的字节数;如果达到尾部返回-1 while ((count=fis.read(buf))!=-1) { System.out.println(new String(buf, 0, count)); } //close 关闭 fis.close(); } }
- FileOutputStream
package study; import java.io.FileOutputStream; public class Demo { public static void main(String[] args) throws Exception { //创建文件字节输出流对象 添加true:每次执行程序不会覆盖原有字节 FileOutputStream fos = new FileOutputStream("d:\\Study",true); String str="helloworld"; //write 写入文件 getBytes 以字符串形式写入 fos.write(str.getBytes()); fos.close(); System.out.println("执行完毕"); } }
实例:
字节流复制文件
package study; import java.io.FileInputStream; import java.io.FileOutputStream; public class Demo { public static void main(String[] args) throws Exception { FileInputStream fis=new FileInputStream("d:\\001.PNG"); FileOutputStream fio=new FileOutputStream("d:\\002.PNG"); byte [] buf=new byte[1024*8]; //计算每次读入个数 int count=0; //边读变写 while ((count=fis.read(buf))!=-1) { fio.write(buf, 0, count); } fis.close(); fio.close(); System.out.println("执行完毕"); } }
-
字节缓冲流
- 缓冲流:BufferedInputStream/BufferedOutputStream
- 提高IO效率,减少访问磁盘的次数
- 数据存储在缓冲区中,flush是将缓冲区的内容写入文件中,也可以直接close
package study; //使用字节缓冲流读取 import java.io.BufferedInputStream; import java.io.FileInputStream; public class Demo { public static void main(String[] args) throws Exception { FileInputStream fis = new FileInputStream("d:\\Study"); //创建缓冲流对象 BufferedInputStream bis = new BufferedInputStream(fis); int data=0; while ((data=bis.read())!=-1) { System.out.print((char)data); } //自定义缓冲区 // byte[] buf = new byte[1024]; // int count = 0; // while ((count = bis.read(buf)) != -1) { // System.out.println(new String(buf, 0, count)); // } bis.close(); } }
package study; //使用字节缓冲流写入文件 import java.io.BufferedOutputStream; import java.io.FileOutputStream; public class Demo { public static void main(String[] args) throws Exception { FileOutputStream fos=new FileOutputStream("d:\\test.txt"); BufferedOutputStream bos=new BufferedOutputStream(fos); //写入十次hello... for (int i = 0; i < 10; i++) { bos.write("helloworld\n".getBytes()); //flush刷新硬盘 bos.flush(); } //关闭(内部调用flush方法) bos.close(); } }
- 缓冲流:BufferedInputStream/BufferedOutputStream
-
对象流
-
对象流:ObjectOutPutStream/ObjectInputStream
- 增强了缓冲区功能
- 增强了读写8中基本数据类型和字符串功能
- 增强了读写对象的功能
使用流传输对象的过程称为序列化丶反序列化
序列化:
package study; import java.io.Serializable; //该接口无实现方法,仅标记为序列化类 public class Student implements Serializable { int age; String name; public Student(int age, String name) { super(); this.age = age; this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Student [age=" + age + ", " + (name != null ? "name=" + name : "") + "]"; } } package study; import java.io.FileOutputStream; import java.io.ObjectOutputStream; /** * 使用objectOutputStream实现对象的序列化 要求:序列化类必须要实现Serializable接口 * * @author badwoman * */ public class Demo { public static void main(String[] args) throws Exception { //bin 表示二进制文件 FileOutputStream fos = new FileOutputStream("d:\\stu.bin"); ObjectOutputStream oos = new ObjectOutputStream(fos); // 序列化(写入操作) Student student = new Student(18, "张三"); //writeObject 写入对象 oos.writeObject(student); oos.close(); System.out.println("序列化完毕"); } }
反序列化:
package study; import java.io.FileInputStream; import java.io.ObjectInputStream; /** * 使用:ObjectInputSteam实现反序列化(读取重构成对象) * * @author badwoman * */ public class Demo { public static void main(String[] args) throws Exception { FileInputStream fis = new FileInputStream("d:\\stu.bin"); ObjectInputStream ois = new ObjectInputStream(fis); Student student = (Student) ois.readObject(); System.out.println("执行完毕"); System.out.println(student.toString()); } }
序列化和反序列化注意事项
package study; import java.io.Serializable; //该接口无实现方法,仅标记为序列化类 public class Student implements Serializable { private static final long serialVersionUID = 300L; int age; String name; public Student(int age, String name) { super(); this.age = age; this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Student [age=" + age + ", " + (name != null ? "name=" + name : "") + "]"; } } package study; import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; /** * 使用objectOutputStream实现对象的序列化 * 注意事项 * 1.序列化类必须要实现Serializable接口 * 2.序列化类中的对象属性要求实现Serializable接口 * 3.序列化版本号Id serialVersionUID,保证序列化的类和反序列化的类是同一个类 * 4.使用transient修饰属性,这个属性不能序列化 * 5.静态属性不能序列化 * 6.序列化多个对象,可以借助集合实现 * @author badwoman * */ public class Demo { public static void main(String[] args) throws Exception { //bin 表示二进制文件 FileOutputStream fos = new FileOutputStream("d:\\stu.bin"); ObjectOutputStream oos = new ObjectOutputStream(fos); // 序列化(写入操作) Student student = new Student(18, "张三"); Student student2 = new Student(22, "李四"); ArrayList<Student>list=new ArrayList<>(); list.add(student); list.add(student2); //writeObject 写入对象 // oos.writeObject(student); oos.writeObject(list); oos.close(); System.out.println("序列化完毕"); } } package study; import java.io.FileInputStream; import java.io.ObjectInputStream; import java.util.ArrayList; /** * 使用:ObjectInputSteam实现反序列化(读取重构成对象) * * @author badwoman * */ public class Demo2 { public static void main(String[] args) throws Exception { FileInputStream fis = new FileInputStream("d:\\stu.bin"); ObjectInputStream ois = new ObjectInputStream(fis); // Student student = (Student) ois.readObject(); ArrayList<Student> list=(ArrayList<Student>) ois.readObject(); System.out.println("执行完毕"); // System.out.println(student.toString()); System.out.println(list.toString()); } }
编码方式
-
转换流
-
桥转换流:InputStreamReader/OutPutStreamWriter
- 可将字节流转换成字符流
- 可设置字符的编码方式
package study; import java.io.FileInputStream; import java.io.InputStreamReader; /** * 使用InputStreamReader读取文件,指定使用的编码 * * @author badwoman * */ public class Demo { public static void main(String[] args) throws Exception { FileInputStream fis = new FileInputStream("d:\\test.txt"); InputStreamReader isr = new InputStreamReader(fis, "utf-8"); int data = 0; while ((data = isr.read()) != -1) { System.out.print((char) data); } isr.close(); } }
package study; import java.io.FileOutputStream; import java.io.OutputStreamWriter; /** * 使用OutputStreamWriter写入文件,指定使用的编码 * * @author badwoman * */ public class Demo { public static void main(String[] args) throws Exception { FileOutputStream fos = new FileOutputStream("d:\\1.txt"); OutputStreamWriter osw = new OutputStreamWriter(fos, "gbk"); for (int i = 0; i < 10; i++) { osw.write("今天也要继续努力\r\n"); osw.flush(); } osw.close(); System.out.println("执行完毕"); } }
-
字符流
-
字符流的父类(抽象类)
- Reader:字符输入流
package study; import java.io.FileReader; /**使用FileReader读取文件 * @author badwoman * */ public class Demo { public static void main(String[] args)throws Exception { FileReader fr=new FileReader("d:\\test.txt"); int data=0; while ((data=fr.read())!=-1) {//读取一个字符 System.out.print((char)data); } // char[] buf=new char[1024]; // int count=0; // while ((count=fr.read(buf))!=-1) { // System.out.println(new String(buf,0,count)); // } // fr.close(); } }
- Writer:字符输出流
package study; import java.io.FileWriter; /**使用FileWriter * @author badwoman * */ public class Demo { public static void main(String[] args)throws Exception { FileWriter fw=new FileWriter("d:\\write.txt"); for (int i = 0; i < 1000; i++) { //write() 写入 fw.write("java\r\n"); fw.flush(); } fw.close(); System.out.println("执行完毕"); } }
-
字符缓冲流
- 缓冲流:BuffereReader/BuffereWrite
- 高效读写
- 支持输入换行符
- 可一次写一行丶读一行
package study; import java.io.BufferedReader; import java.io.FileReader; /** * 使用字符缓冲流读取文件 * BufferedReader * @author badwoman * */ public class Demo { public static void main(String[] args) throws Exception { FileReader fr=new FileReader("d:\\write.txt"); BufferedReader br=new BufferedReader(fr); // char []buf=new char[1024]; // int count=0; // while ((count=fr.read(buf))!=-1) { // System.out.println(new String(buf,0,count)); // } String line=null; //readLine() 一行一行的读取 while ((line=br.readLine())!=null) { System.out.println(line); } br.close(); } }
package study; import java.io.BufferedWriter; import java.io.FileWriter; /** * BufferreWrite * @author badwoman * */ public class Demo { public static void main(String[] args) throws Exception { FileWriter fw=new FileWriter("d:\\Study.txt"); BufferedWriter bw = new BufferedWriter(fw); for (int i = 0; i < 10; i++) { bw.write("今晚状态很好"); bw.newLine(); bw.flush(); } bw.close(); System.out.println("执行完毕"); } }
- 缓冲流:BuffereReader/BuffereWrite
打印流
-
PrintWriter
- 封装了print()/println() 方法,支持写入后换行
- 支持数据原样打印
package study; import java.io.PrintWriter; /** * PrintWriter的使用 * @author badwoman * */ public class Demo { public static void main(String[] args) throws Exception { PrintWriter pw = new PrintWriter("d:\\print.txt"); pw.println(97); pw.println('a'); pw.println(true); pw.close(); System.out.println("执行完毕"); } }
File类
概念:代表物理盘符中的一个文件或者文件夹
package study;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Date;
/**
* File类的使用
* 1.分隔符
* 2.文件操作
* 3.文件夹操作
*
* @author badwoman
*
*/
public class Demo {
public static void main(String[] args) throws Exception {
// separator();
// fileOpe();
directoryOpe();
}
//
//文件操作
// public static void fileOpe() throws IOException, InterruptedException {
// File file = new File("d:\\file.txt");
// System.out.println("创建结果"+file.createNewFile());
//
System.out.println("删除结果"+file.delete());
//
jvm退出时删除
file.deleteOnExit();
阻塞当前线程,休眠5s
Thread.sleep(5000);
//
// //获取文件信息
// System.out.println("获取文件的绝对路径"+file.getAbsolutePath());
// System.out.println("获取路径"+file.getPath());
// System.out.println("获取文件名称"+file.getName());
// System.out.println("获取父目录"+file.getParent());
// System.out.println("获取文件长度"+file.length());
// System.out.println("文件创建时间"+new Date(file.lastModified()).toLocaleString());
//
//判断
// System.out.println("是否可写"+file.canWrite());
// System.out.println("是否是文件"+file.isFile());
// System.out.println("是否隐藏"+file.isHidden());
// }
//文件夹操作
public static void directoryOpe() throws InterruptedException {
File dir = new File("d:\\a\\b\\c");
System.out.println(dir.toString());
//只能创建单级目录
// dir.mkdir();
//创建多级目录
System.out.println("创建结果"+dir.mkdirs());
//删除文件夹 注意:只能删除空目录
//获取文件夹信息
//判断
//遍历文件夹
File dir2 = new File("d:\\思维导图");
//list() 遍历操作
String[] files=dir2.list();
for (String string : files) {
System.out.println(string);
}
System.out.println("----------FileFilter----------");
//匿名内部类制定过滤规则
File[]files2=dir2.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
//endsWith 测试字符串是否以指定的后缀结束
if (pathname.getName().endsWith(".pdf")) {
return true;
}
return false;
}
});
for (File file : files2) {
System.out.println(file);
}
}
}
递归遍历和递归删除
package study;
import java.io.File;
public class Dome {
public static void main(String[] args) {
// lisDir(new File("d:\\a"));
deleteDir(new File("d:\\a"));
}
public static void lisDir(File dir) {
File[] files = dir.listFiles();
// 判断抽象路径
if (files != null && files.length > 0) {
for (File file : files) {
// 判断是否为目录
if (file.isDirectory()) {
lisDir(file);
} else {
System.out.println(file.getAbsolutePath());
}
}
}
}
public static void deleteDir(File dir) {
File [] files=dir.listFiles();
if (files!=null&&files.length>0) {
for (File file : files) {
if (file.isDirectory()) {
deleteDir(file);
}else {
System.out.println(file.getAbsolutePath()+"删除"+file.delete());
}
}
}
System.out.println(dir.getAbsolutePath()+"删除"+dir.delete());
}
}
补充集合
package study;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Properties;
import java.util.Set;
/**
* Properties:属性集合
* 1.存储属性名和属性值
* 2.属性名和属性值都是字符串类型
* 3.没有泛型
* 4.和流有关
* @author badwoman
*
*/
public class Dome {
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
properties.setProperty("name", "张三");
properties.setProperty("age", "18");
//遍历
//keySet
//entrySet
//stringPropertyNames
Set<String>pSet=properties.stringPropertyNames();
for (String pro : pSet) {
System.out.println(pro+"----"+properties.getProperty(pro));
}
//和流有关的方法
//list
// PrintWriter pw = new PrintWriter("d:\\print.txt");
// properties.list(pw);
// pw.close();
//
// //store 保存
// FileOutputStream fos = new FileOutputStream("d:\\store.properties");
// properties.store(fos, "注释");
// fos.close();
//load 加载
Properties properties2 = new Properties();
FileInputStream fis = new FileInputStream("d:\\store.properties");
properties2.load(fis);
}
}