io-FileReader+Filewrite
FileReader
1、文件字符输入流,只能读取普通文本文件,不能读取world文档,声音,图片,视频等
2、while循环后需要将char数组转为String字符串:new Sring(chars,0,readCount);
import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; /* FileReader: 文件字符输入流,只能读取普通文本。 读取文本内容时,比较方便,快捷。 */ public class FileReaderTest { public static void main(String[] args) { FileReader reader = null; try { // 创建文件字符输入流 reader = new FileReader("tempfile"); /// 开始读 char[] chars = new char[4]; // 一次读取4个字符 int readCount = 0; while((readCount = reader.read(chars)) != -1) { System.out.print(new String(chars,0,readCount)); }
} catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
FileWrite :内存到硬盘过程:
1、使用之后要刷新
2、在文件内写入数据时,要在文件之后加一个:true ;避免新数据写入后,情况原来的数据
/* FileWriter: 文件字符输出流。写。 只能输出普通文本。 不能读取声音,图片,视频,world文件都不行 */ public class FileWriterTest { public static void main(String[] args) { FileWriter out = null; try { // 创建文件字符输出流对象 //会先清空 //out = new FileWriter("file"); out = new FileWriter("file", true); // 开始写。 char[] chars = {'我','是','中','国','人'}; out.write(chars); //写出去一部分:"中国人" out.write(chars, 2, 3); out.write("我是一名java软件工程师!"); // 写出一个换行符。 out.write("\n"); out.write("hello world!"); // 刷新 out.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
FileReader+Filewrit 联合使用拷贝文件
1、拷贝的文件只能为普通的文本文件,不能拷贝world文档,声音,图片,视频等
2、Filewrit 写完之后一定:刷新
3、关闭资源时,一定要分开关闭
import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; /* 使用FileReader FileWriter进行拷贝的话,只能拷贝“普通文本”文件。 */ public class Copy02 { public static void main(String[] args) { FileReader in = null; FileWriter out = null; try { // 读 in = new FileReader("chapter23/src/com/bjpowernode/java/io/Copy02.java"); // 写 out = new FileWriter("Copy02.java"); // 一边读一边写: char[] chars = new char[1024 * 512]; // 1MB int readCount = 0; while((readCount = in.read(chars)) != -1){ out.write(chars, 0, readCount); } // 刷新 out.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix