当前位置: 首页 > news >正文

java~IO流

文件

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

 

常用的文件操作

(1)创建文件的相关方法

  1. new File(String pathname) //根据路径构建一个File对象;
  2. new File(File parent,String child) //根据父目录文件+子路径构建一个File对象;
  3. new File(String parent,String child) //根据父目录+子路径构建一个File对象;
  4. 使用createNewFile()创建新文件。
public class FileCreate {public static void main(String[] args) {}//方式1 new File(String pathname)@Testpublic void create01() {String filePath = "e:\\news1.txt";File file = new File(filePath);try {file.createNewFile();System.out.println("文件创建成功");} catch (IOException e) {e.printStackTrace();}}//方式2 new File(File parent,String child) //根据父目录文件+子路径构建//e:\\news2.txt@Testpublic  void create02() {File parentFile = new File("e:\\");String fileName = "news2.txt";//这里的file对象,在java程序中,只是一个对象//只有执行了createNewFile 方法,才会真正的,在磁盘创建该文件File file = new File(parentFile, fileName);try {file.createNewFile();System.out.println("创建成功~");} catch (IOException e) {e.printStackTrace();}}//方式3 new File(String parent,String child) //根据父目录+子路径构建@Testpublic void create03() {//String parentPath = "e:\\";String parentPath = "e:\\";String fileName = "news4.txt";File file = new File(parentPath, fileName);try {file.createNewFile();System.out.println("创建成功~");} catch (IOException e) {e.printStackTrace();}}}

(2)获取文件的相关信息 

public class FileInformation {public static void main(String[] args) {}//获取文件的信息@Testpublic void info() {//先创建文件对象File file = new File("e:\\news1.txt");//调用相应的方法,得到对应信息System.out.println("文件名字=" + file.getName());//getName、getAbsolutePath、getParent、length、exists、isFile、isDirectorySystem.out.println("文件绝对路径=" + file.getAbsolutePath());System.out.println("文件父级目录=" + file.getParent());System.out.println("文件大小(字节)=" + file.length());//按字节计算,utf-8编码下,一个英文字母一个字节,一个汉字三个字节System.out.println("文件是否存在=" + file.exists());//TSystem.out.println("是不是一个文件=" + file.isFile());//TSystem.out.println("是不是一个目录=" + file.isDirectory());//F}
}

(3)目录的操作和文件删除 

  1. mkdir() //创建一级目录(文件夹),返回boolean
  2. mkdirs() //创建多级目录(文件夹),返回boolean
  3. delete() //删除空目录或文件,返回boolean,可同时做判断条件看删除成功与否
public class Directory_ {public static void main(String[] args) {}//判断 d:\\news1.txt 是否存在,如果存在就删除@Testpublic void m1() {String filePath = "e:\\news1.txt";File file = new File(filePath);if (file.exists()) {if (file.delete()) {System.out.println(filePath + "删除成功");} else {System.out.println(filePath + "删除失败");}} else {System.out.println("该文件不存在...");}}//判断 D:\\demo02 是否存在,存在就删除,否则提示不存在//这里我们需要体会到,在java编程中,目录也被当做文件@Testpublic void m2() {String filePath = "D:\\demo02";File file = new File(filePath);if (file.exists()) {if (file.delete()) {System.out.println(filePath + "删除成功");} else {System.out.println(filePath + "删除失败");}} else {System.out.println("该目录不存在...");}}//判断 D:\\demo\\a\\b\\c 目录是否存在,如果存在就提示已经存在,否则就创建@Testpublic void m3() {String directoryPath = "D:\\demo\\a\\b\\c";File file = new File(directoryPath);if (file.exists()) {System.out.println(directoryPath + "存在..");} else {if (file.mkdirs()) { //创建一级目录使用mkdir() ,创建多级目录使用mkdirs()System.out.println(directoryPath + "创建成功..");} else {System.out.println(directoryPath + "创建失败...");}}}//判断 D:\\demo 目录是否存在,如果存在就提示已经存在,否则就创建@Testpublic void m4() {String directoryPath = "D:\\demo";File file = new File(directoryPath);if (file.exists()) {System.out.println(directoryPath + "存在..");} else {if (file.mkdir()) { //创建一级目录使用mkdir() ,创建多级目录使用mkdirs()System.out.println(directoryPath + "创建成功..");} else {System.out.println(directoryPath + "创建失败...");}}}
}

IO流 

流的分类

InputStream 按字节读取效率较慢,                        
OutputStram 如图片/音乐/视频/doc/pdf

体系图

节点流

从一个特定的数据源读写数据,是底层流/低级流,直接跟数据源相接

InputStream(字节输入流)

常用子类 

  • FileInputStram:文件输入流

  • BufferedInputStream:缓冲字节输入流

  • ObjectInputStream:对象字节输入流

FileInputStream

String filePath = "xxx";
//(1)一次读取一个字节
int readData = 0;
//创建 FileInputStream,用于读取文件
FileInputStream fileInputStream = new FileInputStream(filePath);
//从该输入流中读取一个字节的数据。如果返回-1,表示读取完毕。如果没有输入可用,该方法将阻止。
while((readData = fileInputStream.read()) != -1 ) {System.out.print((char)readData);//转成char显示
}//(2)一次读取多个字节
byte[] buf = new byte[8]; //初始化字节数组,如音乐/图片一次读取1024个字节(1kb)
int readLen = 0;
FileInputStream fileInputStream = new FileInputStream(filePath);
//从该输入流读取最多buf.length字节的数据到字节数组。如果返回-1,表示读取完毕。如果没有输入可用,该方法将阻止。
while((readLen = fileInputStream.read(buf)) != -1) {System.out.print(new String(buf, 0, readLen)); //显示:如果读取正常,返回实际读取的字节数
}
//关闭流资源
fileInputStream.close();

OutputStream(字节输出流)

FileOutputStream
//创建FileOutputStream对象,获得输出流
String filePath = "xxx"; //如果文件不存在,会创建文件,前提时目录已存在
FileOutputStream fileOutputStream = new (filePath); //(1)写入内容会覆盖原内容
FileOutputStream fileOutputStream = new (filePath, true);//(2)写入内容会追加原内容
//写入内容
fileOutputStream.write('H'); //(1)写入一个字符,会自动转换成int
String str = "hello, world!"; //(2)写入字符串
fileOutputStream.write(str.getBytes()); //getBytes()把字符串转换为字节数组
fileOutputStream.write(str.getBytes(), 0, 3); //write(byte[] b, int off, int len)将len字节从位于偏移量off的指定字节数组写入此文件输出流
//关闭输出流资源
fileOutputStream.close();

处理流

BufferedInputStream

BufferedOutputStream 

/ * 思考:字节流可以操作二进制文件,可以操作文本文件吗?当然可以*/
public class BufferedCopy02 {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));//循环的读取文件,并写入到 destFilePathbyte[] buff = new byte[1024];int readLen = 0;//当返回 -1 时,就表示文件读取完毕while ((readLen = bis.read(buff)) != -1) {bos.write(buff, 0, readLen);}System.out.println("文件拷贝完毕~~~");} catch (IOException e) {e.printStackTrace();} finally {//关闭流 , 关闭外层的处理流即可,底层会去关闭节点流try {if(bis != null) {bis.close();}if(bos != null) {bos.close();}} catch (IOException e) {e.printStackTrace();}}}
}

字符流

FileReader

 字符读取

int data = 0;
fileReader = new FileReader(filePath);
//循环读取 使用read, 单个字符读取
while ((data = fileReader.read()) != -1) {System.out.print((char) data);

字符数组读取 

int readLen = 0;
char[] buf = new char[8];
//创建FileReader对象
fileReader = new FileReader(filePath);
//循环读取 使用read(buf), 返回的是实际读取到的字符数
while ((readLen = fileReader.read(buf)) != -1) {System.out.print(new String(buf, 0, readLen));

 FileWriter

public class FileWriter_ {public static void main(String[] args) {String filePath = "e:\\note.txt";//创建FileWriter对象FileWriter fileWriter = null;char[] chars = {'a', 'b', 'c'};try {fileWriter = new FileWriter(filePath);//默认是覆盖写入
//            3) write(int):写入单个字符fileWriter.write('H');
//            4) write(char[]):写入指定数组fileWriter.write(chars);
//            5) write(char[],off,len):写入指定数组的指定部分fileWriter.write("韩顺平教育".toCharArray(), 0, 3);
//            6) write(string):写入整个字符串fileWriter.write(" 你好北京~");fileWriter.write("风雨之后,定见彩虹");
//            7) write(string,off,len):写入字符串的指定部分fileWriter.write("上海天津", 0, 2);//在数据量大的情况下,可以使用循环操作.} catch (IOException e) {e.printStackTrace();} finally {//对应FileWriter , 一定要关闭流,或者flush才能真正的把数据写入到文件try {//fileWriter.flush();//关闭文件流,等价 flush() + 关闭fileWriter.close();} catch (IOException e) {e.printStackTrace();}}System.out.println("程序结束...");}
}

处理流  

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

        这个Reader/Writer可以是FileReader/FileWriter,进行一个包装,只要是其子类就可以包装,可以对文件、数组、管道等进行操作。
        处理流包装节点流,使用了修饰器模式,不会直接与数据源相连,消除了不同节点流的实现差异,也提供更方便的方法完成输入输出
        优点1:增加缓冲提高输入输出效率
        优点2:提供方法一次输入输出大批量数据,操作更便捷

模拟修饰器设计模式

//Reader_类
abstract class Reader_ { //抽象类public abstract void read();
}//FileReader_类
class FileReader_ extends Reader_ {public void read() {System.out.println("对文件进行读取...");}
}// StringReader_类
class StringReader_ extends Reader_ {public void read() {System.out.println("读取字符串..");}}// BufferedReader_类
class BufferedReader_{private Reader_ reader_; //属性是 Reader_类型//接收Reader_ 子类对象public BufferedReader_(Reader_ reader_) {this.reader_ = reader_;}//让方法更加灵活, 多次读取文件, 或者加缓冲byte[] ....public void readFiles(int num) {for(int i = 0; i < num; i++) {reader_.read();}}//扩展 readString, 批量处理字符串数据public void readStrings(int num) {for(int i = 0; i <num; i++) {reader_.read();}}}public class Test_ {public static void main(String[] args) {BufferedReader_ bufferedReader_ = new BufferedReader_(new FileReader_());bufferedReader_.readFiles(10);BufferedReader_ bufferedReader_2 = new BufferedReader_(new StringReader_());bufferedReader_2.readStrings(5);}
}

BufferedReader和BufferedWriter属于字符流,是按照字符来读取数据的,不要操作二进制文件
处理流只是包装,操作数据还是节点流,关闭处理流会自动关闭节点流,只需要关闭外层流。

BufferedReader

读取文本文件

public class BufferedReader_ {public static void main(String[] args) throws Exception {String filePath = "e:\\a.java";//创建bufferedReaderBufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));//读取String line; //按行读取, 效率高//说明//1. bufferedReader.readLine() 是按行读取文件//2. 当返回null 时,表示文件读取完毕while ((line = bufferedReader.readLine()) != null) {System.out.println(line);}bufferedReader.close();}
}
BufferedWriter 

写入文本文件

public class BufferedWriter_ {public static void main(String[] args) throws IOException {String filePath = "e:\\ok.txt";//创建BufferedWriter//说明://1. new FileWriter(filePath, true) 表示以追加的方式写入//2. new FileWriter(filePath) , 表示以覆盖的方式写入BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));bufferedWriter.write("hello, world!");bufferedWriter.newLine();//插入一个和系统相关的换行bufferedWriter.write("hello2, world!");bufferedWriter.newLine();bufferedWriter.write("hello3, world!");bufferedWriter.newLine();//说明:关闭外层流即可 , 传入的 new FileWriter(filePath) ,会在底层关闭bufferedWriter.close();}
}

对象处理流 

需求

  • 将int num = 100 的int数据保存到文件中,注意不是100数字,而是int 100,能够从文件中直接恢复int 100
  • 将Dog dog = new Dog{“小黄”, 3}这个dog对象保存到文件中,并且能从文件恢复

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

序列化和反序列化

  • 序列化就是在保存数据时,保存数据的值和数据类型
  • 反序列化就是在恢复数据时,恢复数据的值和数据类型
  • 需要让某个对象支持序列化机制,则必须让其类是可序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一:
                 Serializable //这是一个标记接口,没有方法
                 Externalizable//该接口有方法需要实现,因此我们一般实现上面的Serializable接口

ObjectInputStream

数据反序列化


import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;/*** 演示ObjectInputStream的使用,完成数据的反序列化*/
public class ObjectInputStream_ {public static void main(String[] args) throws IOException, ClassNotFoundException {//使用ObjectInputStream读取data.dat并反序列化恢复数据//1.创建流对象String filePath = "D:\\AAA\\t\\1.dat";//指定反序列化的文件ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));//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());//dog的编译类型是Object, 运行类型是DogObject dog = ois.readObject();System.out.println("dog的运行类型:" + dog.getClass());System.out.println("dog的信息:" + dog);//重要细节//希望调用Dog的方法,需要向下转型 Object -> Dog//ObjectInputStream 和 ObjectOutputStream 需要引用同一个Dog包Dog dog1 = (Dog) dog;System.out.println(dog1.getName());//3.关闭ois.close();}
}

ObjectOutputStream

数据序列化

import java.io.*;
/*** 演示ObjectOutputStream的使用,完成数据的序列化*/
public class ObjectOutputStream_ {public static void main(String[] args) throws IOException {//使用ObjectOutputStream序列化基本数据类型和一个Dog对象(name, age), 并保存到data.dat文件中//序列化后, 保存的数据格式不是纯文本格式,而是按照它自己的格式来保存String filePath = "D:\\AAA\\t\\1.txt";//1.创建流对象ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));//2.写入对象(序列化)oos.writeInt(100);//int 自动装箱->Integer(Integer实现了Serializable接口)oos.writeBoolean(true);oos.writeChar(97);oos.writeChar('a');oos.writeDouble(3.14);oos.writeUTF("韩顺平教育");//保存一个dog对象oos.writeObject(new Dog("小黄", 3));//3.关闭oos.close();System.out.println("数据保存完毕(序列化形式)");}
}
//如果要序列化某个对象,必须实现Serializable接口
class Dog implements Serializable {private String name;private int age;public Dog(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Dog{" +"name='" + name + '\'' +", age=" + age +'}';}
}

 注意事项和细节说明

(1)读写顺序要一致

(2)要求实现序列化或反序列化的对象,需要实现Serializable

(3)序列化的类中建议添加serialVersionUID,目的是提高版本的兼容性

(4)序列化对象时,默认将里面所有属性都进行序列化,但除了static或transient修饰的成员

(5)序列化对象时,要求里面属性的类型也需要实现序列化接口

(6)序列化具备可继承性,也就是如果某类已经实现了序列化,则它的所有子类也已经默认实现

标准输入输出流

Scanner in = new Scanner(System.in);

转换流

在默认情况下,读取文件是按照utf-8编码,若修改文件的编码,原先文件的中文字符就会变为乱码,为了解决这个问题,就需要转换流。

转换流可以把字节流转换成字符流,而字节流可以指定编码方式

InputStreamReader

可以将InputStream(字节流)包装成Reader(字符流)

/*** 演示使用 InputStreamReader 解决中文乱码问题* 将字节流 FileInputStream 转成字符流 InputStreamReader, 并指定编码*/
public class InputStreamReader_ {public static void main(String[] args) throws IOException {//编程将字节流 FileInputStream 包装成(转换成)字符流 InputStreamReader//对文件进行读取(按照utf-8/gbk格式),进而再包装成BufferedReader//上个视频,a.txt的格式已改为ANSI国标码,根据当前系统,为gbk格式编码String filePath = "F:\\a.txt";InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk");BufferedReader br = new BufferedReader(isr);//BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "gbk"));String s = br.readLine();System.out.println("读取到的内容:" + s);br.close();}
}

OutputStreamWriter

可以将OutputStream(字节流)包装成Writer(字符流) 

/*** 演示使用 OutputStreamWriter 指定文件编码方式保存文件*/
public class OutputStreamWriter_ {public static void main(String[] args) throws IOException {//编程将字节流 FileOutputStream 包装成(转换成)字符流 OutputStreamWriter//对文件进行写入(指定保存的编码方式,按照gbk格式)String filePath = "F:\\hsp.txt";String charSet = "gbk";OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), charSet);osw.write("hello 韩顺平教育");osw.close();System.out.println("按照" + charSet + "保存文件成功!");}
}

 打印流

打印流只有输出流,没有输入流 

PrintStream(字节打印流)

package chapter19.printstream;import java.io.IOException;
import java.io.PrintStream;
/*** 演示 PrintStream 使用方式*/
public class PrintStream_ {public static void main(String[] args) throws IOException {PrintStream out = System.out;//默认情况下,PrintStream输出数据的位置是标准输出,即显示器out.print("hello world!");/*public void print(String s) {if (s == null) {s = "null";}write(s);}*///print底层使用write,所以我们可以直接调用write进行打印/输出out.write("hello".getBytes());out.close();//我们可以修改打印流输出的位置System.setOut(new PrintStream("F:\\test.txt"));System.out.println("hello 韩顺平教育!");}
}

PrintWriter

package chapter19.transformation;import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
/*** 演示 PrintWriter 使用方式*/
public class PrintWriter_ {public static void main(String[] args) throws IOException {
//        PrintWriter pw = new PrintWriter(System.out);PrintWriter pw = new PrintWriter(new FileWriter("F:\\a.txt"));pw.print("hello world!");pw.close();//flush + 关闭流,才能将数据写入}
}

 Properties

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

​              配置文件的格式:

                ​ 键=值

​                 键=值

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

(3)常用方法

  • load 加载配置文件的键值对到Properties对象
  • list 将数据显示到指定设备
  • getProperty(key) 根据键获取值
  • setProperty(key,value) 设置键值对到Properties对象
  • store 将Properties中的键值对存储到配置文件,在idea中,保存信息到配置文件,如果含有中文,会存储为unicode码
package chapter19.properties_;import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;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);System.out.println();//根据键获取值String user = properties.getProperty("user");String pwd = properties.getProperty("pwd");System.out.println("用户名:" + user);System.out.println("密码:" + pwd);}
}
package chapter19.properties_;import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;public class Properties03 {public static void main(String[] args) throws IOException {//使用Properties创建配置文件,修改配置文件内容Properties properties = new Properties();//创建properties.setProperty("charset", "uts-8");properties.setProperty("user", "汤姆");//中文保存时,是保存对应的unicode编码properties.setProperty("pwd", "123456");//修改//如果该文件没有key,就是创建//如果该文件有key,就是修改properties.setProperty("pwd", "666666");//将键值对k-v存储到文件中//null表示没有注释,有注释的话会写在文件的最上面,#...properties.store(new FileOutputStream("src\\mysql2.properties"), null);}
}

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • OnlyOffice在线部署
  • C++箭头运算符->
  • 在线短剧APP开发,短剧市场的新赛道新盈利
  • 基于springboot+vue+uniapp的校园快递平台小程序
  • 程序员修炼之路:深入广泛的必修课程
  • 智慧景区导览系统小程序开发
  • Mac设置公钥
  • Linux:shell命令
  • 安装ROS(catkin_pkg找不到)
  • Tkinter简介与实战(1)
  • 正则表达式与文本处理
  • 一句JS代码,实现随机颜色的生成
  • 力扣面试(五)
  • esp8266初始化卡在1的原因
  • CentOS通过rsync实现文件同步(daemon方式)
  • 【剑指offer】让抽象问题具体化
  • Java-详解HashMap
  • js中forEach回调同异步问题
  • Octave 入门
  • October CMS - 快速入门 9 Images And Galleries
  • REST架构的思考
  • RxJS: 简单入门
  • Spring Cloud Alibaba迁移指南(一):一行代码从 Hystrix 迁移到 Sentinel
  • Transformer-XL: Unleashing the Potential of Attention Models
  • 安装python包到指定虚拟环境
  • 多线程事务回滚
  • 离散点最小(凸)包围边界查找
  • 聊聊springcloud的EurekaClientAutoConfiguration
  • 排序算法学习笔记
  • 使用 Node.js 的 nodemailer 模块发送邮件(支持 QQ、163 等、支持附件)
  • 说说动画卡顿的解决方案
  • 通信类
  • 小程序01:wepy框架整合iview webapp UI
  •  一套莫尔斯电报听写、翻译系统
  • 用jquery写贪吃蛇
  • 与 ConTeXt MkIV 官方文档的接驳
  • 智能网联汽车信息安全
  • Play Store发现SimBad恶意软件,1.5亿Android用户成受害者 ...
  • # 利刃出鞘_Tomcat 核心原理解析(七)
  • #define,static,const,三种常量的区别
  • #pragma 指令
  • (Redis使用系列) Springboot 使用redis实现接口幂等性拦截 十一
  • (回溯) LeetCode 40. 组合总和II
  • (蓝桥杯每日一题)平方末尾及补充(常用的字符串函数功能)
  • (论文阅读31/100)Stacked hourglass networks for human pose estimation
  • (十)T检验-第一部分
  • (转)winform之ListView
  • (转)真正的中国天气api接口xml,json(求加精) ...
  • (转载)虚幻引擎3--【UnrealScript教程】章节一:20.location和rotation
  • *Django中的Ajax 纯js的书写样式1
  • .net mvc部分视图
  • .net 反编译_.net反编译的相关问题
  • .NET 设计一套高性能的弱事件机制
  • .net 使用ajax控件后如何调用前端脚本
  • .net 无限分类