I/O流分类:

InputStream和Read的子类都有read(),用来读取单个字节或字节数组

OutputStream和write的子类都有write(),用来写入单个字节或字节数组

一般都是通过装饰器Decorator模式叠加多个对象提供所期望的功能。创建单一的流,却需要创建多个对象

InputStream:

InputStream为字节输入流,一般都是通过其子类实现功能,是所有字节输入流的基类

public abstract class InputStream implements Closeable {
private static final int MAX_SKIP_BUFFER_SIZE = 2048; public abstract int read() throws IOException; //读取1byte的数据,返回int类型。若返回值=-1说明没有读取到任何字节 public int read(byte[] var1) throws IOException {} //读取var1.length个字节的数据放到var1数组中,返回值是读取的字节数 public int read(byte[] var1, int off, int len) throws IOException {} //从输入流中最多读取len个字节的数据,存放到偏移量为off的var1数组中。 public long skip(long var1) throws IOException {} //忽略输入流中的n个字节,返回值是实际忽略的字节数, 跳过一些字节来读取 public int available() throws IOException {} //返回输入流中可以读取的字节数。必须是InputStream的子类调用才行,本身调用返回0 public void close() throws IOException {} //每次读取结束,都要关闭输入流并释放与流相关的资源 }

OutputStream:

OutputStream为字节输出流,一般都是通过其子类实现功能,是所有字节输出流的基类

public abstract class OutputStream implements Closeable, Flushable {
public OutputStream() {} public abstract void write(int var1) throws IOException; //先将int转换为byte类型,把低字节写入到输出流中 public void write(byte[] var1) throws IOException {} //将数组var1中的字节写到输出流 public void write(byte[] var1, int off, int len) throws IOException {} //将数组var1的字节从偏移量off开始的len个字节写到输出流 public void flush() throws IOException { } //将数据缓冲区中数据全部输出,并清空缓冲区 public void close() throws IOException { } //每次写入结束,都要关闭输出流并释放与流相关的资源
}

FileInputStream和FileOutputStream:

public static void main(String[] args) throws IOException {
String pathName = "D:" + File.separator + "a.txt";
File file = new File(pathName);
OutputStream outputStream = new FileOutputStream(file);
outputStream.write("abc1".getBytes());
outputStream.close();
InputStream inputStream = new FileInputStream(file);
byte[] bytes = new byte[1024];
int length = inputStream.read(bytes);
String s = new String(bytes, 0, length);
System.out.println(s);
inputStream.close();
}

输出结果:

我是好人追加内容

FileOutputStream用来从内存区读数据到文件,如果文件存在,会把内容覆盖,如果不存在,创建文件,然后把数据写入

FileInputStream用来从文件读数据到内存区

ByteArrayInputStream和ByteArrayOutputStream:

ByteArrayOutputStream创建的时候,程序内部创建一个byte[]类型的缓冲区,然后向数组中写入或读出byte型数据。

public static void main(String[] args) throws IOException {
OutputStream outputStream = new ByteArrayOutputStream();
outputStream.write("abc".getBytes());
byte[] bytes = ((ByteArrayOutputStream) outputStream).toByteArray();
outputStream.close();
InputStream inputStream = new ByteArrayInputStream(bytes);
byte[] bytes1 = new byte[1024];
int len;
while ((len = inputStream.read(bytes1)) != -1) {
System.out.println(new String(bytes1, 0, len));
}
}

输出结果:abc

可以从得到byte[]缓冲区,然后读取数据,可以向缓冲区多次写入数据,然后集中一次读取

BufferedInputStream、BufferedInputStream:

public static void main(String[] args) throws IOException {
String pathName = "D:" + File.separator + "a.txt";
File file = new File(pathName); BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(new File("D:" + File.separator + "b.txt"))); byte[] bytes = new byte[4];
while (inputStream.read(bytes) != -1) {
System.out.println(new String(bytes));
outputStream.write(bytes);
}
inputStream.close();
outputStream.close();
}

在文件流外面包装一层缓冲流读取函数,先从缓冲区读取数据

PS:在写入缓冲区结束之后,一定要调用flush()或者close(),否则数据一致存在缓冲区,而没有写出

PipedInputStream、PipedOutputStream:

  管道流主要用于连接两个线程的数据通信.通过连接而产生一个通信管道,PipedOutputStream向管道中写入数据,PipedInputStream从管

道中读取数据。管道输出流和管道输入流执行时不能互相阻塞,所以一般要开启独立线程分别执行

public class Sender implements Runnable{
private PipedOutputStream outputStream = new PipedOutputStream();
public PipedOutputStream outputStream() {
return this.outputStream;
}
@Override
public void run() {
try {
outputStream.write("message".getBytes());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Receiver implements Runnable{
private PipedInputStream inputStream = new PipedInputStream();
public PipedInputStream inputStream() {
return this.inputStream;
} @Override
public void run() {
byte[] bytes = new byte[1024];
try {
int len = inputStream.read(bytes);
if (len != -1) {
System.out.println("成功接收:" + new String(bytes));
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Test {
public static void main(String[] args) throws IOException {
Sender sender = new Sender();
Receiver receiver = new Receiver();
PipedOutputStream outputStream = sender.outputStream();
PipedInputStream inputStream = receiver.inputStream();
inputStream.connect(outputStream);
new Thread(sender).start();
new Thread(receiver).start();
}
}

输出结果:

成功接收:message                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         

ObjectInputStream、ObjectOutputStream:

ObjectOutputStream可以把对象直接存入到文件中,然后利用ObjectInputStream读取文件还原成对象

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Student implements Serializable{ private int id;
private String name;
private int sex; @Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public static void main(String[] args) throws Exception {
String pathName = "D:" + File.separator + "a.txt";
File file = new File(pathName);
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(file));
Student student = new Student(1001, "sam", 1);
outputStream.writeObject(student);
outputStream.close(); ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(file));
Student student1 = (Student)inputStream.readObject();
System.out.println(student1);
}

PS:保存的对象必须实现了Serializable接口,否则出现异常:java.io.NotSerializableException: com.it.entity.Student

Java IO(三)--字节流基本使用的更多相关文章

  1. Java IO: 其他字节流(上)

    作者: Jakob Jenkov 译者: 李璟(jlee381344197@gmail.com) 本小节会简要概括Java IO中的PushbackInputStream,SequenceInputS ...

  2. java IO之字节流和字符流-Reader和Writer以及实现文件复制拷贝

    接上一篇的字节流,以下主要介绍字符流.字符流和字节流的差别以及文件复制拷贝.在程序中一个字符等于两个字节.而一个汉字占俩个字节(一般有限面试会问:一个char是否能存下一个汉字,答案当然是能了,一个c ...

  3. java IO(三):字符流

    */ .hljs { display: block; overflow-x: auto; padding: 0.5em; color: #333; background: #f8f8f8; } .hl ...

  4. java IO流——字节流

    字节流主要操作byte类型数据,以byte数组为准,主要操作类有InputStream(字节输入流).OutputSteam(字节输出流)由于IputStream和OutputStream都是抽象类, ...

  5. java IO的字节流和字符流及其区别

    1. 字节流和字符流的概念    1.1 字节流继承于InputStream    OutputStream,    1.2 字符流继承于InputStreamReader    OutputStre ...

  6. [Java IO]02_字节流

    概要 字节流有两个核心抽象类:InputStream 和 OutputStream.所有的字节流类都继承自这两个抽象类. InputStream 负责输入,OutputStream 负责输出. 字节流 ...

  7. Java IO之字节流

    Java中的输入是指从数据源等读到Java程序中,这里的数据源可以是文件,内存或网络连接,输出则是指从Java程序中写到目的地. 输入输出流可以分为以下几种类型(暂时不考虑File类) 类名 中文名 ...

  8. Java IO流-字节流

    2017-11-05 17:48:17 Java中的IO流按数据类型分类分为两种,一是字节流,二是字符流.字符流的出现是为了简化文本数据的读入和写出操作. 如果操作的文件是文本文件,那么使用字符流会大 ...

  9. Java—IO流 字节流

    IO流(输入流.输出流),又分为字节流.字符流. 流是磁盘或其它外围设备中存储的数据的源点或终点. 输入流:程序从输入流读取数据源.数据源包括外界(键盘.文件.网络…),即是将数据源读入到程序的通信通 ...

随机推荐

  1. 并不对劲的bzoj3529:loj2193:p3312:[SDOI2014]数表

    题目大意 定义函数\(f(x)=\sum_{k|x}k\) \(t\)(\(t\leq2*10^4\))组询问,每组给定\(n,m,a\)(\(n,m\leq10^5,a\leq10^9\)),求: ...

  2. BZOJ_2947_[Poi2000]促销_堆

    BZOJ_2947_[Poi2000]促销_堆 Description Bytelandish连锁超市委托你编写一个程序来模拟一项即将施行的促销活动,该活动的规则如下: ●想要参与的顾客,只需把他的个 ...

  3. 深入理解JMM(Java内存模型) --(一)

    并发编程模型的分类 在并发编程中,我们需要处理两个关键问题:线程之间如何通信及线程之间如何同步(这里的线程是指并发执行的活动实体).通信是指线程之间以何种机制来交换信息.在命令式编程中,线程之间的通信 ...

  4. 腾讯API

    相关文档: API列表  腾讯开放平台联调工具集  公共返回码说明 SDK下载

  5. 5950 Recursive sequence (矩阵快速幂)

    题意:递推公式 Fn = Fn-1 + 2 * Fn-2 + n*n,让求 Fn; 析:很明显的矩阵快速幂,因为这个很像Fibonacci数列,所以我们考虑是矩阵,然后我们进行推公式,因为这样我们是无 ...

  6. pytest单侧模块_入门汇总

    Pytest简单介绍 (pytest是python的一个测试框架,主要是用来进行一些小的测试) 安装:pip install -U pytest 查看是否安装成功:pytest --version 运 ...

  7. GDI+ 加载PNG图片

    #include <GdiPlus.h>#pragma comment(lib, "GdiPlus.lib")using namespace Gdiplus; clas ...

  8. ROS学习笔记六:xxx.launch文件详解

    每当我们需要运行一个ROS节点或工具时,都需要打开一个新的终端运行一个命令.当系统中的节点数量不断增加时,每个节点一个终端的模式会变得非常麻烦.那么有没有一种方式可以一次性启动所有节点呢?答案当然是肯 ...

  9. _bzoj3224 Tyvj 1728 普通平衡树【Splay】

    传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=3224 保存splay模版 一刻不停写了一个小时多一点,幸好一遍过了!(其实带着freopen ...

  10. C plus plus sprintf用法

    sprintf int sprintf ( char * str, const char * format, ... ); Write formatted data to string Compose ...