1. InputStream

1.1 说明

InputStream是一个抽象类,具体来讲:

This abstract class is the superclass of all classes representing an input stream of bytes.

其主要子类包括:

AudioInputStream, ByteArrayInputStream, FileInputStream, FilterInputStream, InputStream, ObjectInputStream, PipedInputStream, SequenceInputStream, StringBufferInputStream

1.2 构造函数

其构造函数非常简单,只有一个无参构造函数

  public InputStream() {}
1.3 主要方法

其主要方法与上一篇介绍的BufferedReader相同,不做详细介绍。

int	available()
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
void close()
Closes this input stream and releases any system resources associated with the stream.
void mark(int readlimit)
Marks the current position in this input stream.
boolean markSupported()
Tests if this input stream supports the mark and reset methods.
abstract int read()
Reads the next byte of data from the input stream.
int read(byte[] b)
Reads some number of bytes from the input stream and stores them into the buffer array b.
int read(byte[] b, int off, int len)
Reads up to len bytes of data from the input stream into an array of bytes.
void reset()
Repositions this stream to the position at the time the mark method was last called on this input stream.
long skip(long n)
Skips over and discards n bytes of data from this input stream.

2. OutputStream

2.1 说明

同InputStream一样,OutputStream也是一个抽象类。

This abstract class is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink.

2.2 构造函数

只有一个默认无参构造函数:

OutputStream()
2.3 主要方法
void	close()
Closes this output stream and releases any system resources associated with this stream.
void flush()
Flushes this output stream and forces any buffered output bytes to be written out.
void write(byte[] b)
Writes b.length bytes from the specified byte array to this output stream.
void write(byte[] b, int off, int len)
Writes len bytes from the specified byte array starting at offset off to this output stream.
abstract void write(int b)
Writes the specified byte to this output stream.

3. FileInputStream

3.1 说明

FileInputStream是InputStream的一个子类,实现了对文件的读。

A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment.

FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.

简单翻译一下:

FileInputStream从文件中读取字节,比较适合读取二进制数据,如果要读取字符文件,最好用FileReader。

FileReader下一篇再讲。

3.2 构造函数
FileInputStream(File file)
Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system.
FileInputStream(FileDescriptor fdObj)
Creates a FileInputStream by using the file descriptor fdObj, which represents an existing connection to an actual file in the file system.
FileInputStream(String name)
Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system.

有三个构造函数,其参数分别是文件、文件描述符、字符串

其主要用法如下:

FileInputStream fis = new FileInputStream("d:/123.txt");
FileInputStream fis1 = new FileInputStream(new File("d:/123.txt"));

文件描述符那个不常用,我也不会。

通过看源码,发现字符串那个会默认构造成文件

  public FileInputStream(String paramString)
throws FileNotFoundException
{
this(paramString != null ? new File(paramString) : null);
} public FileInputStream(File paramFile)
throws FileNotFoundException
{
String str = paramFile != null ? paramFile.getPath() : null;
SecurityManager localSecurityManager = System.getSecurityManager();
if (localSecurityManager != null) {
localSecurityManager.checkRead(str);
}
if (str == null) {
throw new NullPointerException();
}
if (paramFile.isInvalid()) {
throw new FileNotFoundException("Invalid file path");
}
this.fd = new FileDescriptor();
this.fd.incrementAndGetUseCount();
this.path = str;
open(str);
}

注意,这两个构造函数都会抛出FileNotFoundException,但如果传的字符串是null,也会抛出空指针异常。

3.3 主要方法
int	available()
Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
void close()
Closes this file input stream and releases any system resources associated with the stream.
protected void finalize()
Ensures that the close method of this file input stream is called when there are no more references to it.
FileChannel getChannel()
Returns the unique FileChannel object associated with this file input stream.
FileDescriptor getFD()
Returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileInputStream.
int read()
Reads a byte of data from this input stream.
int read(byte[] b)
Reads up to b.length bytes of data from this input stream into an array of bytes.
int read(byte[] b, int off, int len)
Reads up to len bytes of data from this input stream into an array of bytes.
long skip(long n)
Skips over and discards n bytes of data from the input stream.

主要方法与BufferedReader相同。

下面是一个简单的代码示例:

	public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("d:/123.txt");
byte[] b = new byte[1000 * 20];
fis.read(b);
System.out.println(new String(b));
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

通常情况下,很少有人直接通过FileInputStream读取文本文件,会通过BufferedReader封装一下。

另外,FileInputStream也会遇到乱码问题,这个下一篇讲InputStreamReader会讲到。

4. FileOutputStream

4.1 说明

FileOutputStream是OutputStream的一个子类,实现对文件的写入。

A file output stream is an output stream for writing data to a File or to a FileDescriptor. Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one FileOutputStream (or other file-writing object) at a time. In such situations the constructors in this class will fail if the file involved is already open.

FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter.

简单翻译

FileOutputStream是用来写文件的,但这个很依赖操作系统,有的操作系统只能操作一个FileOutputStream。FileOutputStream是用来写二进制的,如果要写字符,请使用FileWriter。

4.2 构造函数
FileOutputStream(File file)
Creates a file output stream to write to the file represented by the specified File object.
FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.
FileOutputStream(FileDescriptor fdObj)
Creates a file output stream to write to the specified file descriptor, which represents an existing connection to an actual file in the file system.
FileOutputStream(String name)
Creates a file output stream to write to the file with the specified name.
FileOutputStream(String name, boolean append)
Creates a file output stream to write to the file with the specified name.

如上,有五个构造函数,如果append为true,则追加写文件

FileOutputStream fos = new FileOutputStream("d:/123.txt", true);
4.3 主要方法
void	close()
Closes this file output stream and releases any system resources associated with this stream.
protected void finalize()
Cleans up the connection to the file, and ensures that the close method of this file output stream is called when there are no more references to this stream.
FileChannel getChannel()
Returns the unique FileChannel object associated with this file output stream.
FileDescriptor getFD()
Returns the file descriptor associated with this stream.
void write(byte[] b)
Writes b.length bytes from the specified byte array to this file output stream.
void write(byte[] b, int off, int len)
Writes len bytes from the specified byte array starting at offset off to this file output stream.
void write(int b)
Writes the specified byte to this file output stream.

主要方法也与BufferedWriter相同,其简单用法:

	private void test() {
try {
FileOutputStream fos = new FileOutputStream("d:/123.txt", true);
String s = "礼拜天";
fos.write(s.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}

注意:流要close;不处理乱码。为什么不处理乱码呢?因为这个是读取二进制的,二进制可没有编码的问题。

参考:

Java源码

Java Platform Standard Edition 7 Documentation

通过源码学Java基础:InputStream、OutputStream、FileInputStream和FileOutputStream的更多相关文章

  1. 通过源码学Java基础:BufferedReader和BufferedWriter

    准备写一系列Java基础文章,先拿Java.io下手,今天聊一聊BufferedReader和BufferedWriter BufferedReader BufferedReader继承Writer, ...

  2. 通过源码分析Java开源任务调度框架Quartz的主要流程

    通过源码分析Java开源任务调度框架Quartz的主要流程 从使用效果.调用链路跟踪.E-R图.循环调度逻辑几个方面分析Quartz. github项目地址: https://github.com/t ...

  3. 通过源码浅析Java中的资源加载

    前提 最近在做一个基础组件项目刚好需要用到JDK中的资源加载,这里说到的资源包括类文件和其他静态资源,刚好需要重新补充一下类加载器和资源加载的相关知识,整理成一篇文章. 理解类的工作原理 这一节主要分 ...

  4. 通过源码了解Java的自动装箱拆箱

    什么叫装箱 & 拆箱? 将int基本类型转换为Integer包装类型的过程叫做装箱,反之叫拆箱. 首先看一段代码 public static void main(String[] args) ...

  5. 通过源码安装PostgresSQL

    通过源码安装PostgresSQL 1.1 下载源码包环境: Centos6.8 64位 yum -y install bison flex readline-devel zlib-devel yum ...

  6. 通过源码了解ASP.NET MVC 几种Filter的执行过程

    一.前言 之前也阅读过MVC的源码,并了解过各个模块的运行原理和执行过程,但都没有形成文章(所以也忘得特别快),总感觉分析源码是大神的工作,而且很多人觉得平时根本不需要知道这些,会用就行了.其实阅读源 ...

  7. Linux下通过源码编译安装程序

    本文简单的记录了下,在linux下如何通过源码安装程序,以及相关的知识.(大神勿喷^_^) 一.程序的组成部分 Linux下程序大都是由以下几部分组成: 二进制文件:也就是可以运行的程序文件 库文件: ...

  8. 通过源码了解ASP.NET MVC 几种Filter的执行过程 在Winform中菜单动态添加“最近使用文件”

    通过源码了解ASP.NET MVC 几种Filter的执行过程   一.前言 之前也阅读过MVC的源码,并了解过各个模块的运行原理和执行过程,但都没有形成文章(所以也忘得特别快),总感觉分析源码是大神 ...

  9. 在centos6.7通过源码安装python3.6.7报错“zipimport.ZipImportError: can't decompress data; zlib not available”

    在centos6.7通过源码安装python3.6.7报错: zipimport.ZipImportError: can't decompress data; zlib not available 从 ...

随机推荐

  1. The secret code

    The secret code Input file: stdinOutput file: stTime limit: 1 sec Memory limit: 256 MbAfter returnin ...

  2. Qt之自定义界面(添加自定义标题栏)

    简述 通过上节内容,我们实现了自定义窗体的移动,但是我们缺少一个标题栏来显示窗体的图标.标题,以及控制窗体最小化.最大化.关闭的按钮. 自定义标题栏后,所有的控件我们都可以定制,比如:在标题栏中添加换 ...

  3. 用ffmpeg把H264数据流解码成YUV420P

    在网上找了很久这方面的内容,发现网上的代码都太旧了,所使用的函数旧到连最新版本的ffmpeg都已经不包含了,所以对于我这个初学者来说太坑拉.不过经过多次查找ffmpeg的头文件和结合网上的内容,终于成 ...

  4. 统计nginx日志里流量

    用awk可以,比如,我想统计nginx日志里,今天下午3点0分,这一分钟内,访问的流量(文件的大小) grep "07/Nov/2013:15:00:"  *.log|awk '{ ...

  5. 字符串截取数字和点击radio显示不同内容

    <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> & ...

  6. 小技巧--让JS代码只执行一次

    有时候实在是没办法,就像我这个比赛系统中,有一个弹出框,这个弹出框之外都是模糊的(这是在ajax写出弹出框时,加了一个水印). 然而遇到的问题,也是蹊跷古怪,因为这个弹出框的事件是数据查询事件,但是因 ...

  7. Android 长按setOnItemLongClickListener 注意细节

    Java代码 gridview.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean ...

  8. spring3.0.5的aop使用

    spring3.0.5开始支持jpa2.0了,但是最近笔者在使用他的的时候发现了3.0.5的包与2.5.5相比,有所精简.其他外部的包,我们需要自己下载. AOP必须的spring包 org.spri ...

  9. DevExpress 中根据数据库字典动态生成卡式菜单 z

    第三方的Devexpress套件因为要使用权限机制控制不同用户进入系统显示菜单所以要配合字典数据动态生成.在WEB中这种问题灰常的轻松在winform里就稍微有点不同为了用DEV实现卡式菜单有组的概念 ...

  10. 细雨学习笔记:Jmeter参数化

    目前我用到两种方式: 1)某个参数,值不常改变的,好多地方都用到:请用“用户定义的变量” 用户组,右键--添加--配置原件--用户定义的变量,在这添加. 如何使用呢?在需要用到此参数的地方这样引用: ...