2022.5.5 I/O字符流
字符流
// 传统字节流读取 中文在UTF—8编码中占3个字节,一个字节一个字节的读 psvm(String[] args){ // 1. 创建FileInputStream对象 FileInputSteam fis = new FileInputStream("路径"); // 2. 读取 int data = 0; while((data = fis.read()) != -1){ System.out.println((char)data); //一个字节一个字节的读 } // 3. 关闭 fis.close(); }
字符流的父类(抽象类,解决字节流中文乱码(中文占多个字节))
reader 字符输入流
-
public int read(){} 读单个字符
-
public int read(char[] c){} 读多个字符
-
public int read(char[] b, int off, int len){}
Writer 字符输出流
-
public void write(int n){}
-
public void write(String str){}
-
public void write(char[] c){}
文件字符流
-
FileReader
-
public int read(char[] c)//从流中读取多个字符,将读到内容存入c数组,返回实际读到的字符数;如果达到文件的尾部,则返回-1。
-
package com.xing.字符流; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class Demo01 { public static void main(String[] args) throws IOException { //创建FileReader 文件字符输入流 FileReader fr = new FileReader("d:\\zifu.txt"); //单个字符读取 int data = 0; while((data = fr.read()) != -1){ System.out.println((char)data);// 读取一个字符 } // 3. 关闭 fr.close(); } }
package com.xing.字符流; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class Demo01 { public static void main(String[] args) throws IOException { //创建FileReader 文件字符输入流 FileReader fr = new FileReader("d:\\zifu.txt"); char[] buf = new char[1024];// 字符缓冲区读取 int count = 0; while((count = fr.read(buf))!= -1){ System.out.println(new String(buf, 0, count)); } // 3. 关闭 fr.close(); } }
-
FileWriter :继承自OutputStreamWriter
-
public void write(String str)//一次写多个字符,将b数组中所有字符,写入输出流。
-
package com.xing.字符流; import java.io.FileWriter; import java.io.IOException; public class Demo02 { public static void main(String[] args) throws IOException { // 1. 创建FileWriter对象 FileWriter fw = new FileWriter("d:\\write.txt"); // 2. 写入 for(int i = 0; i < 10; i ++){ fw.write("写入的内容\n"); fw.flush(); } // 3. 关闭 fw.close(); } }
(案例)使用上述内容进行文本文件复制
不能复制图片或二进制文件,使用字节流可以复制任意文件
package com.xing.字符流; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Demo03 { public static void main(String[] args) throws IOException { // 1. 创建 FileReader fr = new FileReader("..."); FileWriter fw = new FileWriter("..."); // 2. 读写 int data = 0; while((data = fr.read()) != -1){ fw.write(data); fw.flush(); } // 3. 关闭 fw.close(); fr.close(); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!