I/O流实操
创建与文件关联的字节输出流对象 FileOutputStream fos = new
FileOutputStream("c:\\cn8.txt"); //创建可以把字符转成字节的转换流对象,并指定编码
OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
调用转换流,把文字写出去,其实是写到转换流的缓冲区中 osw.write("你好");//写入缓冲区。 osw.close();
创建读取文件的字节流对象
字符输出流
字符输入流
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | //字符输入流 读 文本文件的读写(.java .txt...) //1.创建对象 File file= new File( "d:/aa/4.txt" ); //2.创建字符输入流对象 try { FileReader fileReader= new FileReader(file); int a; a= fileReader.read(); //读取一个字符 System.out.println(( char )a); char [] arr= new char [ 3 ]; fileReader.read(arr); //读取多个字符到数组中 System.out.println( new String(arr)); //循环读取文件的内容 while ((a=fileReader.read())!=- 1 ) System.out.println(( char )a); fileReader.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } |
字符输出流+文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | //字符输出流 写出 //1.创建文件对象 File file= new File( "d:/aa/5.txt" ); //2.创建字符输出流 try { FileWriter fileWriter= new FileWriter(file); fileWriter.write( "bb\r\n" ); //换行 fileWriter.write( "呆萌" ); fileWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } 点击并拖拽以移动 //字节输入流 从文件中读数据进来 一个字节一个字节的读取 (图片 视频文件的读写) //(一个英文字符或数字字符对应一个字节 一个中文字对应的是两个字节,所以读中文要用字符流) //1.创建文件对象 File file= new File( "d:/aa/2.txt" ); //2.创建一个输入流对象 try { FileInputStream fileInputStream= new FileInputStream(file); //3.读数据 int a=fileInputStream.read(); //读取下一个字符 读到了返回当前字符的ascII码 读到文件结尾 则返回-1 System.out.println(( char )a); a=fileInputStream.read(); System.out.println(( char )a); //读取多个字节到数组中 byte [] arr= new byte [ 3 ]; fileInputStream.read(arr); //读取3个字节存入arr数组中 System.out.println( new String(arr, 0 , 3 )); //读取整个文件 while ((a=fileInputStream.read())!=- 1 ) System.out.print(( char )a); //关闭文件 fileInputStream.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } |
字节输出流+文件操作
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)