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

IO流(2)

缓冲流

字节缓冲流

利用字节缓冲区拷贝文件,一次读取一个字节:

public class test {public static void main(String [] args) throws IOException  {//利用字节缓冲区来拷贝文件BufferedInputStream bis=new BufferedInputStream(new FileInputStream("a.txt"));BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("c.txt"));//一次读取一个字节int b;while((b=bis.read())!=-1) {bos.write(b);}bos.close();bis.close();}
}

一次读取多个字节:

public class test {public static void main(String [] args) throws IOException  {//利用字节缓冲区来拷贝文件BufferedInputStream bis=new BufferedInputStream(new FileInputStream("a.txt"));BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("c.txt"));//一次读取多个字节int len;byte[] bytes=new byte[1024];while((len=bis.read(bytes))!=-1) {bos.write(bytes,0,len);}bos.close();bis.close();}
}

字符缓冲流

底层自带了长度为8192缓冲区提高性能。

字符缓冲输入流

特有方法:br.readLine()——读取一行数据

public class test {public static void main(String [] args) throws IOException  {//字符缓冲输入流读取文件BufferedReader br=new BufferedReader(new FileReader("a.txt"));String len;while((len=br.readLine())!=null) {System.out.println(len);}//释放资源br.close();}
}

字符缓冲输出流

特有方法:bw.newLine——换行

public class test {public static void main(String [] args) throws IOException  {//利用字符缓冲输出流BufferedWriter bw=new BufferedWriter(new FileWriter("c.txt"));bw.write("1,2,3");bw.newLine();//换行bw.write("4,5,6");//释放资源bw.close();}
}

综合练习

练习1:修改文本顺序

将《出师表》这个文章顺序恢复到新文件中。

分析:两种方法,一种使用ArrayList集合,一种使用TreeMap(Tree中有默认的排序规则)

第一种方法:先读取,再排序,再写入

public class test {public static void main(String [] args) throws IOException  {//读取BufferedReader br=new BufferedReader(new FileReader("a.txt"));String len;ArrayList<String> list=new ArrayList<>();//将读取到的数据放入集合中while((len=br.readLine())!=null) {list.add(len);}br.close();//排序list.sort(new Comparator<String>() {//指定排序规则@Overridepublic int compare(String o1, String o2) {int i1=Integer.parseInt(o1.split("\\.")[0]);	int i2=Integer.parseInt(o2.split("\\.")[0]);	return i1-i2;}});//写入//需要换行写入BufferedWriter bw=new BufferedWriter(new FileWriter("c.txt"));for(String s:list) {bw.write(s);bw.newLine();}bw.close();}
}

第二种方法:利用TreeMap集合,键为序号,值为后面的字符串

public class test {public static void main(String [] args) throws IOException  {//读取BufferedReader br=new BufferedReader(new FileReader("a.txt"));String len;TreeMap<Integer, String> tm=new TreeMap<>();while((len=br.readLine())!=null) {//将键值放入tm中int i=Integer.parseInt(len.split("\\.")[0]);String j=len.split("\\.")[1];tm.put(i, j);}br.close();//读取BufferedWriter bw=new BufferedWriter(new FileWriter("c.txt"));//获取键值对,利用循环Set<Map.Entry<Integer, String>> entries=tm.entrySet();for(Map.Entry<Integer, String> entry:entries) {String value=entry.getValue();bw.write(value);bw.newLine();}bw.close();}
}

练习2:软件运行次数

实现一个验证程序运行次数的小程序,要求如下:
当程序运行超过3次时给出提示:本软件只能免费使用3次,欢迎您注册会员后继续使用~2.程序运行演示如下:
第一次运行控制台输出:欢迎使用本软件第1次使用免费~
第二次运行控制台输出:欢迎使用本软件第2次使用免费~
第三次运行控制台输出:欢迎使用本软件,第3次使用免费~
第四次及之后运行控制台输出:本软件只能免费使用3次,欢迎您注册会员后继续使用~
分析:

这是一个计数器问题,利用count++完成,但如果将count写入到程序中,运行控制台重新运行后,count将恢复原始数据0,所以需要将count写入到文件中,利用读写完成。

public class test {public static void main(String [] args) throws IOException  {BufferedReader br=new BufferedReader(new FileReader("c.txt"));String c=br.readLine();//读取文件中count的值int count=Integer.parseInt(c);count++;if(count<=3) {System.out.println("欢迎使用本软件第"+count+"次使用免费~");}else {System.out.println("本软件只能免费使用3次,欢迎您注册会员后继续使用~");}//将读取的count++值再写入文件中BufferedWriter bw=new BufferedWriter(new FileWriter("c.txt"));bw.write(count+"");//加入一个“”是将count变为字符串bw.close();}
}

转换流

作用:字节流想要使用字符流中的方法。

利用转换流按照指定字符编码读取,只做了解

练习::手动创建一个GBK的文件,把文件中的中文读取到内存中,不能出现乱码需求

方法1:转换流,只做了解

public class test {public static void main(String [] args) throws IOException  {//利用转换流进行编码转换InputStreamReader isr=new InputStreamReader(new FileInputStream("c.txt"),"GBK");//指定读码的字符集int ch;while((ch=isr.read())!=-1) {System.out.print((char)ch);}isr.close();}
}

 方法2:利用字符流按照指定编码读取(JDK11)

public class test {public static void main(String [] args) throws IOException  {//字符流按照指定字符编码读取FileReader fr =new FileReader("c.txt",Charset.forName("gbk"));int ch;while((ch=fr.read())!=-1) {System.out.println((char)ch);}fr.close();}
}

练习:把一段中文按照GBK的方式写到本地文件。

方法1:转换流

public class test {public static void main(String [] args) throws IOException  {//利用转换流OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("c.txt"),"GBK");osw.write("你好");osw.close();}
}

方法2:字符流

public class test {public static void main(String [] args) throws IOException  {//利用转换流FileWriter fw=new FileWriter("c.txt",Charset.forName("GBK"));fw.write("你好");fw.close();}
}

练习3:利用字节流读取文件中的数据,每次读一整行,而且不能出现乱码
 

public class test {public static void main(String [] args) throws IOException  {//利用字节流读取文件中的数据,每次读一整行,而且不能出现乱码//先是字节流,再是转换流,再是缓冲字符流BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream("c.txt")));String str;while((str=br.readLine())!=null) {System.out.println(str);}br.close();}
}

序列化流

package test02;
import java.io.Serializable;
public class Student implements Serializable{private String name;private int age;public Student() {}public Student(String name,int age) {this.setName(name);this.setAge(age);}@Overridepublic String toString() {return "Student [name=" + name + ", 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;}
}
public class test {public static void main(String [] args) throws IOException  {//序列化流:将一个java对象写入到文件中//先创建对象Student s=new Student("张三",23);//再创建序列流ObjectOutputStream os=new ObjectOutputStream(new FileOutputStream("c.txt"));os.writeObject(s);os.close();}
}

反序列化流

public class test {public static void main(String [] args) throws IOException, ClassNotFoundException  {//反序列化流ObjectInputStream oi=new ObjectInputStream(new FileInputStream("c.txt"));//读取Student o=(Student)oi.readObject();System.out.println(o);oi.close();}
}

练习:用对象流读写多个对象
将多个自定义对象序列化到文件中,但是由于对象的个数不确定,反序列化流该如何读取呢?

分析:由于对象的不确定性,所以将对象放入Arraylist集合中,在读取的时候调用集合。

package test02;
import java.io.Serializable;
public class Student implements Serializable{private String name;private int age;public Student() {}public Student(String name,int age) {this.setName(name);this.setAge(age);}@Overridepublic String toString() {return "Student [name=" + name + ", 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;}
}

先将list集合中的内容写入文件

public class test {public static void main(String [] args) throws IOException, ClassNotFoundException  {//序列化Student s1=new Student("zhangsan",23);Student s2=new Student("lisi",24);Student s3=new Student("wangwu",25);//利用集合将对象存放在集合中ArrayList<Student> list=new ArrayList<>();list.add(s1);list.add(s2);list.add(s3);//创建序列化对象ObjectOutputStream os=new ObjectOutputStream(new FileOutputStream("c.txt"));os.writeObject(list);os.close();}
}

package test02;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;public class read {public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {//读取ObjectInputStream oi=new ObjectInputStream(new FileInputStream("c.txt"));ArrayList<Student> s=(ArrayList<Student>)oi.readObject();for(Student student:s) {System.out.println(student);}}}

http://www.lryc.cn/news/360512.html

相关文章:

  • 【docker】docker启动bitnami/mysql
  • 边缘计算、云计算、雾计算在物联网中的作用
  • 【c语言】探索内存函数
  • day46 完全背包理论基础 518. 零钱兑换 II 377. 组合总和 Ⅳ
  • 【linux】运维-基础知识-认知hahoop周边
  • Python自动实时查询预约网站的剩余名额并在有余额时发邮件提示
  • Flutter 验证码输入框
  • 如何从0到设计一个CRM系统
  • Numba 的 CUDA 示例 (2/4):穿针引线
  • 项目的各个阶段如何编写标准的Git commit消息
  • Python课设-学生信息管理系统
  • openssl 常用命令demo
  • 【Linux】Linux基本指令2
  • springboot+vue+mybatis博物馆售票系统+PPT+论文+讲解+售后
  • java—MyBatis框架
  • 如何使用Spring Cache优化后端接口?
  • 大话C语言:第21篇 数组
  • transfomer中attention为什么要除以根号d_k
  • iperf3带宽压测工具使用
  • [数据集][目标检测]焊接处缺陷检测数据集VOC+YOLO格式3400张8类别
  • 2024华为OD机试真题-剩余银饰的重量-C++(C卷D卷)
  • 糖果促销【百度之星】/思维
  • 【python学习】安装Anaconda后,如何进行环境管理(命令行操作及图形化操作Anaconda Navigator)及包管理
  • HTML大雪纷飞
  • 问界新M7 Ultra仅售28.98万元起,上市即交付
  • 【Java数据结构】详解LinkedList与链表(四)
  • ssm汉服文化平台网站
  • 如何让 LightRoom 每次导入照片后不自动弹出 SD 卡 LR
  • elasticdump和ESM
  • Java扩展机制:SPI与Spring.factories详解