Java学习-IO流-字节输出流
创始人
2024-05-24 17:33:18
0

Java学习-IO流-IO流的体系和字节输出流基本用法

//IO流 → 字节流 → 字节输入流:InputStream
//  ↘	       ↘ 字节输出流:OutputStream
//	  ↘ 字符流 → 字符输入流:Reader
//		       ↘ 字符输出流:Writer

FileInputStream:操作本地文件的字节输入流
FileOutputStream:操作本地文件的字节输出流

FileOutputStream

1.创建字节输出流对象
2.写数据
3.释放资源

public static void main(String[] args) throws IOException{//创建对象FileOutputStream fos = new FileOutputStream("...\\xx.txt");//指定文件路径//写数据fos.write(97);//释放资源fos.close();//xx.txt: a,ASCII码 a=97
}

FileOutputStream 原理

1.创建对象时,在程序和文件之间建立数据传输通道
2.write:写数据,进行数据传输
3.close:取消建立通道

FileOutputStream 书写细节

创建对象:
1.参数是 字符串表示的路径 或者是 File对象 都可以

public FileOutputStream(String name)throws FileNotFoundException{this(name!=null ? new File(name) : null,false);
}
public FileOutputStream(File file)throws FileNotFoundException{this(file,false);
}

两种方式底层调用的都是:

public FileOutputStream(File file,boolean append)throws FileNotFoundException{...}

2.如果文件不存在,会创建一个新的文件,前提是父级路径是存在的
3.如果文件已经存在,则清空文件,再写入数据

写数据:
1.write 方法的参数是整数,实际上写到本地文件中的是整数在ASCII上对应的字符
2.如果想写入97而不是a

fos.write(57);// 9
fos.write(55);// 7

释放资源:

//fos.close();
while(true){}

如果没有释放资源,系统没有解除资源占用,在程序运行时删除 .txt将会提示:操作无法完成,因为文件已在…中打开。

fos.close();
while(true){}

如果释放了资源,解除了资源占用,在程序运行时也可以删除 .txt文件

FileOutputStream 写数据的3种方式

void write(int b):一次写一个字节数据
void write(byte[] b):一次写一个字节数组数据
void write(byte[] b,int off,int len):一次写一个字节数组的部分数据

FileOutputStream fos = new FileOutputStream("...\\xx.txt");
fos.write(97);// abyte[] bytes = {97,98,99,100,101};
fos.write(bytes);// abcdefos.write(bytes,1,2);// bcfos.close();

换行 - \n

FileOutputStream fos = new FileOutputStream("...\\xx.txt");
String str = "hello";
String wrap = "\n";
String str2 = "world"
byte[] arr = str.getBytes();
byte[] arr2 = wrap.getBytes();
byte[] arr3 = str2.getBytes();
fos.write(arr);// hello
fos.write(arr2);
fos.write(arr3);// hello \n world
fos.close();

续写

public FileOutputStream(File file,boolean append){}

第二个参数 append,续写开关,默认为 false,创建对象会清空文件
修改为 true,不会清空文件

// xx.txt : hello
FileOutputStream fos = new FileOutputStream("...\\xx.txt",true);
String str = "world";
byte[] arr = str.getBytes();
fos.write(arr);
fos.close();
// xx.txt : helloworld

相关内容

热门资讯

监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
【PdgCntEditor】解... 一、问题背景 大部分的图书对应的PDF,目录中的页码并非PDF中直接索引的页码...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...
修复 爱普生 EPSON L4... L4151 L4153 L4156 L4158 L4163 L4165 L4166 L4168 L4...
MFC文件操作  MFC提供了一个文件操作的基类CFile,这个类提供了一个没有缓存的二进制格式的磁盘...