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. 转:Android设置全局变量

    声明:本文转自feiyangxiaomi的博客:http://blog.csdn.net/feiyangxiaomi/article/details/9966215仅供学习使用,转载请指明原作者. 文 ...

  2. Jqgrid入门-别具特色的Pager Bar (四)

    Pager Bar位于表格最下边.默认情况下,分为三部分.如图: 第一部分:导航按钮栏(Navigator) 第二部分:页码栏(Pager) 第三部分:记录信息栏(Record)         要实 ...

  3. 50个python库

    50个很棒的Python模块,包含几乎所有的需要:比如Databases,GUIs,Images, Sound, OS interaction, Web,以及其他.推荐收藏. Graphical in ...

  4. HTTP请求头host解析

    Host: 域名 Host表示请求的服务器网址:   request headers中的host字段 例如有user.xiaoqiang.com,hotel.xiaoqiang.com 现在需要登录后 ...

  5. php yii .htaccess

    RewriteEngine on # if a directory or a file exists, use it directlyRewriteCond %{REQUEST_FILENAME} ! ...

  6. POJ 2388 Who's in the Middle (快速选择算法:O(N)求数列第K大)

    [题意]求数列中间项. ---这里可以扩展到数列第K项. 第一次做的时候直接排序水过了= =--这一次回头来学O(N)的快速选择算法. 快速选择算法基于快速排序的过程,每个阶段我们选择一个数为基准,并 ...

  7. python中的类和实例

    今天花了两个多小时后搜索相关博客看了看python中有关类和实例的介绍,差不多大概明白了. python中的类和c++中的类是一样的,不同之处就是c++的类,如果含有成员变量,并且成员变量发生变化后, ...

  8. 【原创】回溯线搜索 Backtracking line search

    机器学习中很多数值优化算法都会用到线搜索(line search).线搜索的目的是在搜索方向上找到是目标函数\(f(x)\)最小的点.然而,精确找到最小点比较耗时,由于搜索方向本来就是近似,所以用较小 ...

  9. FileReader乱码

    出现原因:FileReader读取文件的过程中,FileReader继承了InputStreamReader,但并没有实现父类中带字符集参数的构造函数,所以FileReader只能按系统默认的字符集来 ...

  10. Mem Cgroup目录无法清理问题分析

    http://blogs.360.cn/360xitong/2013/05/02/mem-cgroup%E7%9B%AE%E5%BD%95%E6%97%A0%E6%B3%95%E6%B8%85%E7% ...