Java学习-Day23(IO流)

IO流

文件

  • 什么是文件

    文件是保存数据的地方

  • 文件流

    文件在程序中是以流的形式来操作的

    流:数据在数据源(文件)和程序(内存)之间经历的路径

    输入流:数据从数据源(文件)到程序(内存)的路径

    输出流:数据从程序(内存)到数据源(文件)的路径

常用的文件操作

  • 创建文件对象相关构造器和方法

    • 相关方法

      1. new File(String pathname)//根据路径构建一个File对象
      2. new File(File parent,String child)//根据父目录文件+子路径构建
      3. new File(String parent,String child)//根据父目录+子路径构建
      4. createNewFile 创建新文件
      public class CreateFiles {
          public static void main(String[] args) {
              //方式一  new File(String pathname)
              File file1 = new File("e:\\new1.txt");
              //方式二 new File(File parent,String child)
              File parentFile = new File("e:\\");
              String childFileName = "new2.txt";
              File file2 = new File(parentFile, childFileName);
              //方式三 new File(String parent,String child)
              String parentFileName1 = "e:\\";
              String childFileName1 = "new3.txt";
              File file3 = new File(parentFileName1, childFileName1);
      
              //这里的 file 对象, 在 java 程序中, 只是一个对象
      		//只有执行了 createNewFile 方法, 才会真正的, 在磁盘创建该文件
              
              
              try {
                  file1.createNewFile();
                  System.out.println("new1.txt创建成功");
              } catch (IOException e) {
                  e.printStackTrace();
              }
      
              try {
                  file2.createNewFile();
                  System.out.println("new2.txt创建成功");
              } catch (IOException e) {
                  e.printStackTrace();
              }
              try {
                  file3.createNewFile();
                  System.out.println("new3.txt创建成功");
              } catch (IOException e) {
                  e.printStackTrace();
              }
      
          }
      }
      
  • 获取文件的相关信息

    1. getName—获取文件名字
    2. getAbsolutePath—获取绝对路径
    3. getParent—获取父级目录
    4. length—获取字节长度
    5. exists—文件是否存在
    6. isFile–是不是文件
    7. isDirectory—是不是目录
  • 目录的操作和文件删除

    delete — 删除空目录或文件(在java中目录也被当做文件对待)

    mkdir — 创建一级目录(如e:\a)

    mkdirs — 创建多级目录(如e:\a\b\c,此时a不存在)

IO流原理及流的分类

  • Java IO 流原理

    1. I/O是Input/Output的缩写,I/O技术是非常实用的技术,用于处理数据传输。如读/写文件,网络通讯等。
    2. Java程序中,对于数据的输入/输出操作以”流(stream)”的方式进行。
    3. java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过方法输入或输出数据
    4. 输入input:读取外部数据(磁盘、光盘等存储设备的数据)到程序(内存)中。
    5. 输出output:将程序(内存)数据输出到磁盘、光盘等存储设备中
  • 流的分类

    • 按操作数据单位不同分为:字节流(8 bit)—二进制文件,字符流(按字符)—文本文件
    • 按数据流的流向不同分为:输入流,输出流
    • 按流的角色的不同分为:节点流,处理流/包装流
      在这里插入图片描述
    1. Java的IO流共涉及40多个类,实际上非常规则,都是从如上4个抽象基类派生的。
    2. 由这四个类派生出来的子类名称都是以其父类名作为子类名后缀。

IO流常用的类

  • InputStream:字节输入流

    InputStream抽象类是所有类字节输入流的超类

  • InputStream常用的子类

    1. FileInputStream :文件输入流
    2. BUfferedInputStream:缓冲字节输入流
    3. ObjectInputStream:对象字节输入流
FileInputStream(字节输入流 文件–>程序)
 /*
*
* 演示读取文件...
* 单个字节的读取, 效率比较低
* -> 使用 read(byte[] b)
*/
@Test
public void readFile01() {
String filePath = "e:\\hello.txt";
int readData = 0;
FileInputStream fileInputStream = null;
try {
//创建 FileInputStream 对象, 用于读取 文件
fileInputStream = new FileInputStream(filePath);
//从该输入流读取一个字节的数据。 如果没有输入可用, 此方法将阻止。
//如果返回-1 , 表示读取完毕
while ((readData = fileInputStream.read()) != -1) {
System.out.print((char)readData);//转成 char 显示
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭文件流, 释放资源.
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} /*
*
* 使用 read(byte[] b) 读取文件, 提高效率
*/
@Test
public void readFile02() {
String filePath = "e:\\hello.txt";
//字节数组
byte[] buf = new byte[8]; //一次读取 8 个字节.
int readLen = 0;
FileInputStream fileInputStream = null;
try {
//创建 FileInputStream 对象, 用于读取 文件
fileInputStream = new FileInputStream(filePath);
//从该输入流读取最多 b.length 字节的数据到字节数组。 此方法将阻塞, 直到某些输入可用。
//如果返回-1 , 表示读取完毕
//如果读取正常, 返回实际读取的字节数
while ((readLen = fileInputStream.read(buf)) != -1) {
System.out.print(new String(buf, 0, readLen));//显示
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭文件流, 释放资源.
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileOutputStream
public void writeFile() {
//创建 FileOutputStream 对象
String filePath = "e:\\a.txt";
FileOutputStream fileOutputStream = null;
try {
//得到 FileOutputStream 对象 对象
//老师说明
//1. new FileOutputStream(filePath) 创建方式, 当写入内容是, 会覆盖原来的内容
//2. new FileOutputStream(filePath, true) 创建方式, 当写入内容是, 是追加到文件后面
fileOutputStream = new FileOutputStream(filePath, true);
//写入一个字节
//fileOutputStream.write('H');//
//写入字符串
String str = "hsp,world!";
//str.getBytes() 可以把 字符串-> 字节数组
//fileOutputStream.write(str.getBytes());
/*
write(byte[] b, int off, int len) 将 len 字节从位于偏移量 off 的指定字节数组写入此文件输出流
*/
fileOutputStream.write(str.getBytes(), 0, 3);
 //从索引0开始写3个字符进去
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

文件的拷贝:

  1. 创建文件输入流,
  2. 创建文件输入流
//1. 创建文件的输入流 , 将文件读入到程序
//2. 创建文件的输出流, 将读取到的文件数据, 写入到指定的文件.
String srcFilePath = "e:\\Koala.jpg";
String destFilePath = "e:\\Koala3.jpg";
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(srcFilePath);
fileOutputStream = new FileOutputStream(destFilePath);
//定义一个字节数组,提高读取效果
byte[] buf = new byte[1024];
int readLen = 0;
while ((readLen = fileInputStream.read(buf)) != -1) {
//读取到后, 就写入到文件 通过 fileOutputStream
//即, 是一边读, 一边写
fileOutputStream.write(buf, 0, readLen);//一定要使用这个方法
} 
System.out.println("拷贝 ok~");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//关闭输入流和输出流, 释放资源
if (fileInputStream != null) {
fileInputStream.close();
} if
(fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
FileReader和FileWriter(字符流,按照字符来操作io)
FileReader 相关方法
  1. new FileReader(File/String)
  2. read:每次读取单个字符,返回该字符,如果到文件末尾返回-1
  3. read(char[]):批量读取多个字符到数组,返回读取到的字符数,如果到文件末尾返回-1

相关APl:

  1. new String(char[]):将char[]转换成String
  2. new String(char[],off,len):将char[]的指定部分转换成String
FileWriter常用方法
  1. new FileWriter(File/String):覆盖模式,相当于流的指针在首端,每次new,目标文件都会清空一次
  2. new FileWriter(File/String,true):追加模式,相当于流的指针在尾端
  3. write(int):写入单个字符
  4. write(char):写入指定数组
  5. write(char[],off,len):写入指定数组的指定部分
  6. write (string):写入整个字符串
  7. write(string,off,len):写入字符串的指定部分

相关API: String类:toCharArray:将String转换成char[]

注意:FileWriter使用后,必须要关闭(close)或刷新(flush),否则写入不到指定的文件!

节点流和处理流

  1. 节点流可以从一个特定的数据源读写数据,如FileReader、FileWriter

  2. 处理流(也叫包装流)是“连接”在已存在的流(节点流或处理流)之上,为程序提供更为强大的读写功能,也更加灵活,如BufferedReader、BufferedWriter

    BufferedReader类中,有属性Reader,即可以封装一个节点流,该节点流可以是任意的,只要是Reader子类

节点流和处理流的区别和联系

1.节点流是底层流/低级流,直接跟数据源相接。
2.处理流(包装流)包装节点流,既可以消除不同节点流的实现差异,也可以提供更方便的方法来完成输入输出。[源码理解]
3.处理流(也叫包装流)对节点流进行包装,使用了修饰器设计模式,不会直接与数据源相连[模拟修饰器设计模式=》小伙伴就会非常清楚.]

处理流的功能只要体现在以下两个方面:

1、性能的提高:主要以增加缓冲的方式来提高输入输出的效率。
2、操作的便捷:处理流可能提供了一系列便捷的方法来一次输入输出大批量的数据,使用更加灵活方便

处理流相当于是集大成者,扩展或者集成了更多功能。

BufferedReader和BufferedWriter

BufferedReader、BufferedWriter属于字符流,是按照字符来读取数据的;关闭时处理流,只需要关闭外层流即可,因为底层会自动关闭节点流

BufferedReader方法

String filePath = "e:\\a.java";
//创建 bufferedReader
BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
//读取
String line; //按行读取, 效率高
//说明
//1. bufferedReader.readLine() 是按行读取文件
//2. 当返回 null 时, 表示文件读取完毕
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
} 
//关闭流, 这里注意, 只需要关闭 BufferedReader , 因为底层会自动的去关闭 节点流
bufferedReader.close();

BufferedWriter方法

BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));  
bufferedWriter.write("hello, 韩顺平教育!");
bufferedWriter.newLine();//插入一个和系统相关的换行
//1. new FileWriter(filePath, true) 表示以追加的方式写入
//2. new FileWriter(filePath) ,表示以覆盖的方式写入  
//说明: 关闭外层流即可 , 传入的 new FileWriter(filePath) ,会在底层关闭
bufferedWriter.close();

实现文本文件拷贝

//老韩说明
//1. BufferedReader 和 BufferedWriter 是按照字符操作
//2. 不要去操作 二进制文件[声音, 视频, doc, pdf ], 可能造成文件损坏
//BufferedInputStream
//BufferedOutputStream
String srcFilePath = "e:\\a.java";
String destFilePath = "e:\\a2.java";
// String srcFilePath = "e:\\0245_韩顺平零基础学 Java_引出 this.avi";
// String destFilePath = "e:\\a2 韩顺平.avi";
BufferedReader br = null;
BufferedWriter bw = null;
String line;
try {
br = new BufferedReader(new FileReader(srcFilePath));
bw = new BufferedWriter(new FileWriter(destFilePath));
//说明: readLine 读取一行内容, 但是没有换行
while ((line = br.readLine()) != null) {
//每读取一行, 就写入
bw.write(line);
//插入一个换行
bw.newLine();
} 
System.out.println("拷贝完毕...");
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流
try {
if(br != null) {
br.close();
} if(
bw != null) {
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedInputStream和BufferedOutputStream

BufferedInputStream是字节流在创建BufferedlnputStream 时,会创建一个内部缓冲区数组.

BufferedOutputStream是字节流,实现缓冲的输出流,可以将多个字节写入底层输出流中,而不必对每次字节写入调用底层系统

//copy图片文件
public static void main(String[] args) {
// String srcFilePath = "e:\\Koala.jpg";
// String destFilePath = "e:\\hsp.jpg";
// String srcFilePath = "e:\\0245_韩顺平零基础学 Java_引出 this.avi";
// String destFilePath = "e:\\hsp.avi";
String srcFilePath = "e:\\a.java";
String destFilePath = "e:\\a3.java";
//创建 BufferedOutputStream 对象 BufferedInputStream 对象
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//因为 FileInputStream 是 InputStream 子类
bis = new BufferedInputStream(new FileInputStream(srcFilePath));
bos = new BufferedOutputStream(new FileOutputStream(destFilePath));
//循环的读取文件, 并写入到 destFilePath
byte[] buff = new byte[1024];
int readLen = 0;
//当返回 -1 时, 就表示文件读取完毕
while ((readLen = bis.read(buff)) != -1) {
bos.write(buff, 0, readLen);
} S
ystem.out.println("文件拷贝完毕~~~");
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流 , 关闭外层的处理流即可, 底层会去关闭节点流
try {
if(bis != null) {
bis.close();
} if(
bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
对象流

看一个需求
1、将int num = 100这个 int数据保存到文件中,注意不是100 数字,而是 int 100,并且,能够从文件中直接恢复int 100(而不是字符串或者其他类型)

2、将Dog dog = new Dog(“小黄”,3)这个dog对象保存到文件中,并且能够从文件恢复.

3、上面的要求,就是能够将基本数据类型或者对象进行序列化和反序列化操作

序列化和反序列化

1、序列化就是在保存数据时,保存数据的值和数据类型

2、反序列化就是在恢复数据时,恢复数据的值和数据类型

3、需要让某个对象支持序列化机制,则必须让其类是可序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一:
Serializable //这是一个标记接口,没有方法
Externalizable//该接口有方法需要实现,因此我们一般实现上面的 Serializable接口

//演示 ObjectOutputStream 的使用, 完成数据的序列化
//序列化后, 保存的文件格式, 不是存文本, 而是按照他的格式来保存
String filePath = "e:\\data.dat";
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
//序列化数据到 e:\data.dat
oos.writeInt(100);// int -> Integer (实现了 Serializable)
oos.writeBoolean(true);// boolean -> Boolean (实现了 Serializable)
oos.writeChar('a');// char -> Character (实现了 Serializable)
oos.writeDouble(9.5);// double -> Double (实现了 Serializable)
oos.writeUTF("韩顺平教育");//String
//保存一个 dog 对象
oos.writeObject(new Dog("旺财", 10, "日本", "白色"));//Dog类应该实现Serializable接口
oos.close()
System.out.println("数据保存完毕(序列化形式)");
//使用ObjectlnputStream 读取data.dat并反序列化恢复数据
//1.创建流对象
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src\\data.dat"));
// 2.读取, 注意顺序
//读取(反序列化)的顺序需要和保存数据(序列化)的顺序一致,否则会出现异常
System.out.println(ois.readInt());
System.out.println(ois.readBoolean());
System.out.println(ois.readChar());
System.out.println(ois.readDouble());
System.out.println(ois.readUTF());
System.out.println(ois.readObject());
System.out.println(ois.readObject());
System.out.println(ois.readObject());
//如果需要调用Dog的方法,需要向下转型
//需要将Dog的定义放在可以引用的位置
// 3.关闭
ois.close();
System.out.println("以反序列化的方式读取(恢复)ok~");

注意事项和细节:

  1. 读写顺序要一致
  2. 要求序列化或反序列化的对象,需要实现Serializable
  3. 序列化的类中建议添加SerialVersionUID,为了提高版本的兼容性
  4. 序列化对象时,默认将里面所有属性都进行序列化,但除了static或transient修饰的成员
  5. 序列化对象时,要求里面属性的类型也需要实现序列化接口
  6. 序列化具备可继承性,也就是如果某类已经实现了序列化,则它的所有子类也已经默认实现了序列化
标准输入和输出流

System.in 标准输入 类型:InputStream 默认设备:键盘

System.out 标准输出 类型:PrintStream 默认设备:显示器

转换流InputStreamReader和OutputStreamWriter
public class CodeQuestion {
public static void main(String[] args) throws IOException {
//读取 e:\\a.txt 文件到程序
//思路
//1. 创建字符输入流 BufferedReader [处理流]
//2. 使用 BufferedReader 对象读取 a.txt
//3. 默认情况下, 读取文件是按照 utf-8 编码
String filePath = "e:\\a.txt";
BufferedReader br = new BufferedReader(new FileReader(filePath));
String s = br.readLine();
System.out.println("读取到的内容: " + s);
br.close();
//InputStreamReader
//OutputStreamWriter
}
}
  1. InputStreamReader : Reader的子类,可以将InputStream(字节流)包装成(转换)Reader(字符流)
  2. OutputStreamWriter : Writer的子类,实现将OutputStream (字节流)包装成Writer(字符流)
  3. 当处理纯文本数据时,如果使用字符流效率更高,并且可以有效解决中文问题,所以建议将字节流转换成字符流
  4. 可以在使用时指定编码格式(比如utf-8, gbk , gb2312, ISO8859-1等)

编程将字节流FilelnputStream 包装成(转换成)字符流InputStreamReader,对文件进行读取(按照utf-8/gbk格式),进而在包装成 BufferedReader InputStreamReader_java

/**
* 演示使用 InputStreamReader 转换流解决中文乱码问题
* 将字节流 FileInputStream 转成字符流 InputStreamReader, 指定编码 gbk/utf-8
*/
public class InputStreamReader_ {
public static void main(String[] args) throws IOException {
String filePath = "e:\\a.txt";
//解读
//1. 把 FileInputStream 转成 InputStreamReader
//2. 指定编码 gbk
//InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk");
//3. 把 InputStreamReader 传入 BufferedReader
//BufferedReader br = new BufferedReader(isr);
//将 2 和 3 合在一起
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(filePath), "gbk"));
//4. 读取
String s = br.readLine();
System.out.println("读取内容=" + s);
//5. 关闭外层流
br.close();
}
}
//1.创建流对象
String charSet = "gbk";
OutputStreamWriter osw =
new OutputStreamWriter(new FileOutputStream("d:\\a.txt"), charSet);
// 2.写入
osw.write("hello,韩顺平教育~");
// 3.关闭
osw.close();
System.out.println("保存成功~");
打印流 PrintStream(字节流)和PrintWriter(字符流)(二者只有输出流没有输入流)
public class PrintStream_ {
public static void main(String[] args) throws IOException {
PrintStream out = System.out;
//在默认情况下, PrintStream 输出数据的位置是 标准输出, 即显示器
/*
public void print(String s) {
if (s == null) {
s = "null";
} w
rite(s);
}
*/
out.print("john, hello");
//因为 print 底层使用的是 write , 所以我们可以直接调用 write 进行打印/输出
out.write("韩顺平,你好".getBytes());
out.close();
//我们可以去修改打印流输出的位置/设备
//1. 输出修改成到 "e:\\f1.txt"
//2. "hello, 韩顺平教育~" 就会输出到 e:\f1.txt
//3. public static void setOut(PrintStream out) {
// checkIO();
// setOut0(out); // native 方法, 修改了 out
// }
System.setOut(new PrintStream("e:\\f1.txt"));
System.out.println("hello, 韩顺平教育~");
}
}
printWriter.print("hi, 北京你好~~~~");
printWriter.close();//flush + 关闭流, 才会将数据写入到文件..
}
}
public class PrintWriter_ {
public static void main(String[] args) throws IOException {
//PrintWriter printWriter = new PrintWriter(System.out);//显示到屏幕
PrintWriter printWriter = new PrintWriter(new FileWriter("e:\\f2.txt"));//存到f2.txt
printWriter.print("hello");
printWriter.close();//一定要有close才能写入
}
}

Properties类

mysql.properties

  • 基本格式

    1. 专门用于读写配置文件的集合类

      配置文件的格式:

      键=值

      键=值

    2. 注意:键值对不需要有空格,值不需要用引号,默认类型是String

    3. 常见方法:

      • load: 加载配置文件的键值对到Properties对象
      • list:将数据显示到指定设备
      • getProperty(key):根据键获取值
      • setProperty(key,value):设置键值对到Properties对象(key存在相当于修改value,key不存在相当于添加)
      • store:将Properties中的键值对存储到配置文件,在idea 中,保存信息到配置文件,如果含有中文,会存储为unicode码
  • public class Properties02 {
    public static void main(String[] args) throws IOException {
    //使用 Properties 类来读取 mysql.properties 文件
    //1. 创建 Properties 对象
    Properties properties = new Properties();
    //2. 加载指定配置文件
    properties.load(new FileReader("src\\mysql.properties"));
    //3. 把 k-v 显示控制台
    properties.list(System.out);
    //4. 根据 key 获取对应的值
    String user = properties.getProperty("user");
    String pwd = properties.getProperty("pwd");
    System.out.println("用户名=" + user);
    System.out.println("密码是=" + pwd);
    }
    }
    
  • public class Properties03 {
    public static void main(String[] args) throws IOException {
    //使用 Properties 类来创建 配置文件, 修改配置文件内容
    Properties properties = new Properties();
    //创建
    //1.如果该文件没有 key 就是创建
    //2.如果该文件有 key ,就是修改
    /*
    Properties 父类是 Hashtable , 底层就是 Hashtable 核心方法
    public synchronized V put(K key, V value) {
    // Make sure the value is not null
    if (value == null) {
    throw new NullPointerException();
    } //
    Makes sure the key is not already in the hashtable.
    Entry<?,?> tab[] = table;
    int hash = key.hashCode();
    int index = (hash & 0x7FFFFFFF) % tab.length;
    @SuppressWarnings("unchecked")
    Entry<K,V> entry = (Entry<K,V>)tab[index];
    for(; entry != null ; entry = entry.next) {
    if ((entry.hash == hash) && entry.key.equals(key)) {
    V old = entry.value;
    entry.value = value;//如果 key 存在, 就替换
    return old;
    }
    } a
    ddEntry(hash, key, value, index);//如果是新 k, 就 addEntry
    return null;
    }
    */
    properties.setProperty("charset", "utf8");
    properties.setProperty("user", "汤姆");//注意保存时, 是中文的 unicode 码值
    properties.setProperty("pwd", "888888");
    //将 k-v 存储文件中即可
    properties.store(new FileOutputStream("src\\mysql2.properties"), null);//null可以换成注释 String类型
    System.out.println("保存配置文件成功~");
    }
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晚来舟Mango

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值