java的outputstream_java 输出流 outputstream

一:输入和输出概念

输入流(inputstream):对于java程序来说,从程序写入文件叫做输出。

输出流(outputstream):对于java程序来说,从文件读取数据,到java程序叫做输入。

二:字节流输出(outputstream)

该类是抽象类,public abstract class OutputStream extends Object implements Closeable, Flushable

所以如果想调用他的方法,需要通过子类来进行调用,该类的操作是字节,所以叫做字节输出流

操作文件可以是任意文件。

1:方法:

1127a8c091472f7b9152a6091aa63709.png

1: close()关闭字节输出流,释放资源,类似python中操作文件,最后需要close一样。

2:write()该方法为重载方法,将相应的内容写入文件中。

3:flush()是将缓存的数据刷入永久存储(文件)中。

:2:查看其实现类:

实现类有如下:

f6cc8eb2c1fed74e223e19eb5fe447ab.png

我先来使用:FileOutoutStream类。

public class FileOutputStream

extends OutputStream

构造器:

8782d33025f1b0bfdf89dbfc8598193f.png

如上构造器,通过绑定文件句柄。来实现文件操作。

1 package test14;2

3 import java.io.File;4 import java.io.FileNotFoundException;5 import java.io.FileOutputStream;6 import java.io.OutputStream;7

8 public classOutputStreamDemon {9 public static voidmain(String...args){10

11 }12 public static voidoutputStrem(File file) throws FileNotFoundException{13 FileOutputStream fps=newFileOutputStream(file);14 FileOutputStream fps1=new FileOutputStream("c:\\new");15

16 }17 }

其中append参数的含义:

848d7593f173e0dde20a9b8e20abd63c.png

如果写true表示在文本的最后追加写入。不是覆盖写入!

1 FileOutputStream fps1=new FileOutputStream("c:\\new",true);

1 package test14;2

3 import java.io.*;4

5 public classOutputStreamDemon {6 public static voidmain(String...args){7 File file=new File("c:\\new");8 try{9 outputStrem(file);10 }catch(IOException ex){11 System.out.print(ex);12 }13

14

15 }16 public static voidoutputStrem(File file) throws FileNotFoundException,IOException{17 OutputStream fps=newFileOutputStream(file);18 OutputStream fps1=new FileOutputStream("c:\\new",true);//append 默认写true 表示写入内容追加到文件末尾。

19 byte[] w_con=new byte[]{'o','k'};//写入文件内容需要字节数组。

20 fps1.write(w_con);21 fps1.write(65);//写的数字转换成字母。

22 fps1.close();//关闭文件句柄 释放资源.

23

24 }25 }

输出结果:

f4621dfd04bf3c05ca605b4ac690bbdd.png

换行:

1 byte[] w_con=new byte[]{'o','\n','k'};//写入文件内容需要字节数组。

27a451d2920b7fdeed0c07ce6216ce62.png

在写入字节的时候,写入的内容会对比ASCII表,转换成对应的值写入文件。

cbdd87e18bdccd490eb141d1640c4a5e.png

1 package Fileout_Demo;2

3 import java.io.File;4 import java.io.FileOutputStream;5 import java.io.IOException;6

7 public classFieloutstream_Demo {8 public static voidmain (String...args){9 try{10 write_Test();11 }catch(IOException e){12 System.out.print(e);13 }14

15 }16

17 public static voidwrite_Test() throws IOException{18 File f=new File("c:/tmp.txt");19 FileOutputStream fs=newFileOutputStream(f);20 fs.write("ok".getBytes());//将字符串转换成对应的字节数组。如果是数字的话会按照assic表来写入对应的值。

21 fs.close();22 }23

24 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值