JavaSE-17.3.2【字节流常用的构造方法和写数据的三种方式】
1 package day8.lesson3; 2 3 import java.io.File; 4 import java.io.FileNotFoundException; 5 import java.io.FileOutputStream; 6 import java.io.IOException; 7 8 /* 9 3.3 字节流常用的构造方法和写数据的三种方式 10 11 构造方法 12 FileOutputStream(String name) 13 FileOutputStream(File file) 14 15 写数据的三种方式 16 void write(int b) 17 将指定的字节写入此文件输出流,一次写一个字节数据 18 void write(byte[] b) 19 将b.length字节从指定的字节数组写入此文件输出流,一次写一个字节数组数据 20 void write(byte[] b, int off, int len) 21 将len字节从指定的字节数组开始,从偏移量off(索引)开始写入此文件输出流,一次写一个字节数组的部分数据 22 */ 23 public class FileOutputStreamDemo02 { 24 public static void main(String[] args) throws IOException { 25 FileOutputStream fos = new FileOutputStream("stage2\\src\\day8\\lesson3\\fos2.txt"); 26 /* 27 public FileOutputStream(String name) throws FileNotFoundException { 28 this(name != null ? new File(name) : null, false); 29 } 30 即文件已存在时不会再重新创建文件 31 */ 32 33 /*File file = new File("stage2\\src\\day8\\lesson3\\fos2.txt"); 34 FileOutputStream fos2 = new FileOutputStream(file); 35 // FileOutputStream fos2 = new FileOutputStream(new File("stage2\\src\\day8\\lesson3\\fos2.txt")); 36 //该构造方法实质与第一种构造方法的内部实现相同 37 fos2.close();*/ 38 39 //写入方式1 40 fos.write(97); 41 fos.write(98); 42 fos.write(99); 43 fos.write(100); 44 fos.write(101); 45 //'a' 'b' 'c' 'd' 'e' 46 47 //写入方式2 48 byte[] bytes = {102, 103, 104}; 49 fos.write(bytes); //'f' 'g' 'h';既然是数组,也可以理解为"fgh" 50 51 //PS:str.getBytes()返回字符串对应的字节数组 52 byte[] bytes1 = "ABCDEF".getBytes(); 53 fos.write(bytes1); 54 55 //写入方式3 56 fos.write(bytes1, 0, bytes1.length); 57 fos.write(bytes1, 1, 3); 58 59 fos.close(); 60 } 61 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!