佛山建设网站公司网络推广公司名字大全
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