#字节流

字节输出流FileOutputStream

创建输出流对象

OutputStream 流对象是一个抽象类,不能实例化。所以,我们要找一个具体的子类 :FileOutputStream。 查看FileOutputStream的构造方法:

FileOutputStream(File file)
FileOutputStream(String name)

创建字节输出流对象了做了几件事情:

  1. 调用系统功能去创建文件

  2. 创建字节输出流对象

  3. 把该字节输出流对象引用指向这个文件

public class OutputStreamDemo {
public static void main(String[] args) throws IOException {
OutputStream fos = new FileOutputStream("demo1.txt");
/*
* 创建字节输出流对象了做了几件事情:
* A:调用系统功能去创建文件
* B:创建fos对象
* C:把fos对象指向这个文件
*/ //写数据
fos.write("hello,IO".getBytes());
fos.write("java".getBytes()); //释放资源
//关闭此文件输出流并释放与此流有关的所有系统资源。
fos.close();
/*
* 为什么一定要close()呢?
* A:让流对象变成垃圾,这样就可以被垃圾回收器回收了
* B:通知系统去释放跟该文件相关的资源
*/
//java.io.IOException: Stream Closed
//fos.write("java".getBytes());
}
}
  • 为什么一定要close()呢?
  1. 让流对象变成垃圾,这样就可以被垃圾回收器回收了

  2. 通知系统去释放跟该文件相关的资源

写出数据

字节输出流操作步骤:

  1. 创建字节输出流对象

  2. 写数据

  3. 释放资源

FileOutputStream中的写出方法:

public void write(int b) //写一个字节
public void write(byte[] b) //写一个字节数组
public void write(byte[] b,int off,int len) //写一个字节数组的一部分
public class OutputStreamDemo2 {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("demo2.txt"); // 调用write()方法
fos.write(97); //97 -- 底层二进制数据 -- 通过记事本打开 -- 找97对应的字符值 -- a //public void write(byte[] b):写一个字节数组
byte[] bys={98,99,100,101};
fos.write(bys); //public void write(byte[] b,int off,int len):写一个字节数组的一部分
fos.write(bys,1,3); //释放资源
fos.close();
}
}

如何实现数据的换行?不同的系统针对不同的换行符号识别是不一样的?

windows:\r\n
linux:\n
Mac:\r
public class OutputStreamDemo3 {
public static void main(String[] args) throws IOException {
// 创建一个向具有指定 name 的文件中写入数据的输出文件流。
// 如果第二个参数为 true,则将字节写入文件末尾处,而不是写入文件开始处。
FileOutputStream fos = new FileOutputStream("demo2.txt",true); // 写数据
for (int x = 0; x < 10; x++) {
fos.write(("hello" + x).getBytes());
fos.write("\r\n".getBytes());
} //释放资源
fos.close();
}
}

加入异常处理的字节输出流操作

public class OutputStreamDemo4 {
public static void main(String[] args) throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("demo1.txt");
fos.write("java".getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 如果fos不是null,才需要close()
if (fos != null) {
// 为了保证close()一定会执行,就放到这里了
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

字节输入流FileInputStream

  • 字节输入流操作步骤:
  1. 创建字节输入流对象

  2. 调用read()方法读取数据,并把数据显示在控制台

  3. 释放资源

  • 读取数据的方式:
int read() //一次读取一个字节
int read(byte[] b) //一次读取一个字节数组
  • 一次读取一个字节
public class InputStreamDemo {
public static void main(String[] args) throws IOException {
InputStream fis=new FileInputStream("demo1.txt");
int by = 0;
// 读取,赋值,判断
while ((by = fis.read()) != -1) {
System.out.print((char) by);
} // 释放资源
fis.close();
}
}
一次读取一个字节数组
public class InputStreamDemo2 {
public static void main(String[] args) throws IOException {
FileInputStream fis=new FileInputStream("demo1.txt");
//数组的长度一般是1024或者1024的整数倍
byte[] bys = new byte[1024];
int len = 0;
while ((len = fis.read(bys)) != -1) {
System.out.print(new String(bys, 0, len));
} // 释放资源
fis.close();
}
}

带缓冲区的字节流BufferedOutputStream

public class BufferedOutputStreamDemo {
public static void main(String[] args) throws IOException {
BufferedOutputStream bos=new
BufferedOutputStream(new FileOutputStream("demo1.txt"));
bos.write("hello".getBytes());
bos.close();
}
}

带缓冲区的字节流BufferedInputStream

public class BufferedInputStreamDemo {
public static void main(String[] args) throws IOException {
BufferedInputStream bis=new
BufferedInputStream(new FileInputStream("demo1.txt"));
int by=-1;
while((by=bis.read())!=-1){
System.out.print((char)by);
}
bis.close();
}
}

复制文件

public class CopyFile {
public static void main(String[] args) throws IOException {
String strFile="国旗歌.mp4";
String destFile="demo3.mp4";
long start = System.currentTimeMillis();
//copyFile(strFile,destFile); //共耗时:75309毫秒
//copyFile2(strFile,destFile); //共耗时:153毫秒
//copyFile3(strFile,destFile);//共耗时:282毫秒
copyFile4(strFile,destFile);//共耗时:44毫秒
long end = System.currentTimeMillis();
System.out.println("共耗时:" + (end - start) + "毫秒");
} /**
* 基本字节流一次读写一个字节
*/
public static void copyFile(String srcFile,String destFile) throws IOException {
FileInputStream fis=new FileInputStream(srcFile);
FileOutputStream fos=new FileOutputStream(destFile); int by=0;
while((by=fis.read())!=-1){
fos.write(by);
} fis.close();
fos.close();
} /**
* 基本字节流一次读写一个字节数组
*/
public static void copyFile2(String srcFile,String destFile) throws IOException{
FileInputStream fis=new FileInputStream(srcFile);
FileOutputStream fos=new FileOutputStream(destFile); int len=0;
byte[] bys=new byte[1024];
while((len=fis.read(bys))!=-1){
fos.write(bys,0,len);
} fis.close();
fos.close();
} /**
* 高效字节流一次读写一个字节
*/
public static void copyFile3(String srcFile,String destFile) throws IOException{
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(srcFile));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(destFile)); int by=0;
while((by=bis.read())!=-1){
bos.write(by);
} bis.close();
bos.close();
} /**
* 高效字节流一次读写一个字节数组
*/
public static void copyFile4(String srcFile,String destFile) throws IOException{
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(srcFile));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(destFile)); int len=0;
byte[] bys=new byte[1024];
while((len=bis.read(bys))!=-1){
bos.write(bys,0,len);
} bis.close();
bos.close();
}
}

装饰者模式

Java I/O 使用了装饰者模式来实现。以 InputStream 为例,

  • InputStream 是抽象组件;
  • FileInputStream 是 InputStream 的子类,属于具体组件,提供了字节流的输入操作;
  • FilterInputStream 属于抽象装饰者,装饰者用于装饰组件,为组件提供额外的功能。例如 BufferedInputStream 为 FileInputStream 提供缓存的功能。

实例化一个具有缓存功能的字节流对象时,只需要在 FileInputStream 对象上再套一层 BufferedInputStream 对象即可。

FileInputStream fileInputStream = new FileInputStream(filePath);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);

DataInputStream 装饰者提供了对更多数据类型进行输入的操作,比如 int、double 等基本类型。

免费Java高级资料需要自己领取,涵盖了Java、Redis、MongoDB、MySQL、Zookeeper、Spring Cloud、Dubbo高并发分布式等教程,一共30G。
传送门:https://mp.weixin.qq.com/s/JzddfH-7yNudmkjT0IRL8Q

字节输出流FileOutputStream的更多相关文章

  1. 字节输出流 FileOutputStream

    输入和输出 : 参照物 都是java程序来参照 output 内存---->硬盘 input 持久化数据-->内存 字节流输出 定义:流按照方向可以分为输入和输出流 字节流 :可以操作任何 ...

  2. 一切皆为字节和字节输出流_OutputStream类&FileOutputStream类介绍

    一切皆为字节 一切文件数据(文本.图片.视频等)在存储时,都是以二进制数字的形式保存,都一个一个的字节,那么传输时一样如此.所以,字节流可以传输任意文件数据.在操作流的时候,我们要时刻明确,无论使用什 ...

  3. java 20 - 9 带有缓冲区的字节输出流和字节输入流

    由之前字节输入的两个方式,我们可以发现,通过定义数组读取数组的方式比一个个字节读取的方式快得多. 所以,java就专门提供了带有缓冲区的字节类: 缓冲区类(高效类) 写数据:BufferedOutpu ...

  4. java 20 - 6 加入了异常处理的字节输出流的操作

    昨天坐了十几个钟的车回家,累弊了.... ————————————割掉疲劳————————————— 前面的字节输出流都是抛出了异常不管,这次的加入了异常处理: 首先还是创建一个字节输出流对象,先给它 ...

  5. java 20 - 5 字节输出流写出数据的一些方法

    首先回顾下 字节输出流操作步骤:  A:创建字节输出流对象  B:调用write()方法  C:释放资源 创建字节流输出对象 FileOutputStream fos = new FileOutput ...

  6. Java输出流FileOutputStream使用详解

    Java输出流FileOutputStream使用详解 http://baijiahao.baidu.com/s?id=1600984799323133994&wfr=spider&f ...

  7. FileOutputSream文件字节输出流

    1.FileOutputSream文件字节输出流:  输入--写出--使用:  输出--写入--存储: 写出写入是对硬盘而言: 其中,OutputStream为所有类型的字节输出流的超类: FileO ...

  8. 021.2 IO流——字节输出流

    内容:流的分类,文件写入(字节输出流),异常处理,获取一个文件夹下的特定文件集合 字节流的抽象基类:InputStream,OutputStream字符流的抽象基类:Reader,Writer由这四个 ...

  9. java IO流 之 字节输出流 OutputString()

    Java学习重点之一:OutputStream 字节输出流的使用 FileOutPutStream:子类,写出数据的通道 步骤: 1.获取目标文件 2.创建通道(如果原来没有目标文件,则会自动创建一个 ...

随机推荐

  1. 使用Lambda解决_inbound_nodes错误

    Keras出现了下面的错误: AttributeError: 'NoneType' object has no attribute '_inbound_nodes' 原因是使用了Keras backe ...

  2. v8/src/compilation-statistics.cc pdfium编译

    v8/src/compilation-statistics.cc:18:3: 警告:‘auto’ changes meaning in C++11; please remove it [-Wc++0x ...

  3. python27期day07:基础数据类型补充、循环删除的坑、二次编码、作业题。

    1.求最大位数bit_length: a = 10 #8421 1010print(a.bit_length())结果:42.capitalize首字母变大写: s = "alex" ...

  4. window.devicePixelRatio ,px,rem

    window属性:devicePixelRatio 设备像素比 https://www.w3cschool.cn/fetch_api/fetch_api-atvq2nma.html devicePix ...

  5. Python进阶-VI 生成器函数进阶、生成器表达式、推导式

    一.生成器函数进阶 需求:求取移动平均数 1.应用场景之一,在奥运会气枪射击比赛中,每打完一发都会显示平均环数! def show_avg(): print('你已进入显示移动平均环数系统!') a ...

  6. 怎么删除STL容器的元素

    在STL容器有顺序容器和关联容器两种. 顺序容器删除元素的方法有两种: 1.c.erase(p) 从c中删除迭代器p指定的元素.p必须指向c中一个真实元素,不能等于c.end().返回一个指向p之后元 ...

  7. xBIM之二:构建墙和门窗

    研究了两天,终于实现了利用xBIM自动输出墙和门窗 比较粗糙的源码如下: private void Form1_Load(object sender, EventArgs e) { //first c ...

  8. [LeetCode] 727. Minimum Window Subsequence 最小窗口序列

    Given strings S and T, find the minimum (contiguous) substring W of S, so that T is a subsequence of ...

  9. [LeetCode] 33. Search in Rotated Sorted Array 在旋转有序数组中搜索

    Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e. ...

  10. 一键脚本解决Windows系统更新错误(0x80070003)

    新建文本,写入以下内容并保存为bat文件 REM 解决系统更新错误(0x80070003) pause net stop "Windows Update" rd /s/q &quo ...