通过源码学Java基础:InputStream、OutputStream、FileInputStream和FileOutputStream
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的更多相关文章
- 通过源码学Java基础:BufferedReader和BufferedWriter
准备写一系列Java基础文章,先拿Java.io下手,今天聊一聊BufferedReader和BufferedWriter BufferedReader BufferedReader继承Writer, ...
- 通过源码分析Java开源任务调度框架Quartz的主要流程
通过源码分析Java开源任务调度框架Quartz的主要流程 从使用效果.调用链路跟踪.E-R图.循环调度逻辑几个方面分析Quartz. github项目地址: https://github.com/t ...
- 通过源码浅析Java中的资源加载
前提 最近在做一个基础组件项目刚好需要用到JDK中的资源加载,这里说到的资源包括类文件和其他静态资源,刚好需要重新补充一下类加载器和资源加载的相关知识,整理成一篇文章. 理解类的工作原理 这一节主要分 ...
- 通过源码了解Java的自动装箱拆箱
什么叫装箱 & 拆箱? 将int基本类型转换为Integer包装类型的过程叫做装箱,反之叫拆箱. 首先看一段代码 public static void main(String[] args) ...
- 通过源码安装PostgresSQL
通过源码安装PostgresSQL 1.1 下载源码包环境: Centos6.8 64位 yum -y install bison flex readline-devel zlib-devel yum ...
- 通过源码了解ASP.NET MVC 几种Filter的执行过程
一.前言 之前也阅读过MVC的源码,并了解过各个模块的运行原理和执行过程,但都没有形成文章(所以也忘得特别快),总感觉分析源码是大神的工作,而且很多人觉得平时根本不需要知道这些,会用就行了.其实阅读源 ...
- Linux下通过源码编译安装程序
本文简单的记录了下,在linux下如何通过源码安装程序,以及相关的知识.(大神勿喷^_^) 一.程序的组成部分 Linux下程序大都是由以下几部分组成: 二进制文件:也就是可以运行的程序文件 库文件: ...
- 通过源码了解ASP.NET MVC 几种Filter的执行过程 在Winform中菜单动态添加“最近使用文件”
通过源码了解ASP.NET MVC 几种Filter的执行过程 一.前言 之前也阅读过MVC的源码,并了解过各个模块的运行原理和执行过程,但都没有形成文章(所以也忘得特别快),总感觉分析源码是大神 ...
- 在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 从 ...
随机推荐
- Android Material Design-TabLayout的使用
TabLayout 位于 android.support.design.widget.TabLayout. 一般与 ViewPager 结合在一起使用.以前有开源库 viewpagerindicato ...
- nodejs抓网易NBA数据
var http = require("http");var cheerio = require("cheerio"); var url = "htt ...
- jquery ajax请求 清除缓存
使用jquery里load方法或者ajax调用页面的时候会存在cache的问题,清除cache的方法: 调用jQuery.ajaxSetup ({cache:false}) 方法即可.
- 函数fil_extend_space_to_desired_size
/**********************************************************************//** Tries to extend a data f ...
- BZOJ2253: [2010 Beijing wc]纸箱堆叠
题解: 其实就是求三维偏序最长链.类似于三维逆序对,我们可以用树状数组套平衡树来实现. DP方程 :f[i]=max(f[j]+1) a[j]<a[i] 我们按一维排序,另一位建立树状数组,把第 ...
- HttpContext.Current.RewritePath方法重写URL
if (!IsPostBack) { //如果请求ID为空,则重写URL为:~/index.aspx?ID=shouji.115sou.com if (Request.QueryString[&quo ...
- Web Api 中使用 PCM TO WAV 的语音操作
/// <summary> /// 语音[文件.上传.解码.保存(WAV)] /// </summary> [DeveloperEx("Liwei:秘书语音需求单&q ...
- 原创: 做一款属于自己风格的音乐播放器 (HTML5的Audio新特性)
灵感的由来是前些天看到了博: http://www.cnblogs.com/li-cheng 的首页有一个很漂亮的播放器,感觉很不错,是用Flex做的Flash播放器. 于是我也便想到了,自己也来来弄 ...
- apache开源项目-- Turbine
1.缘起 Jetspeed是Apache Jakarta小组的开放源码门户系统.它使得最终用户可以通过WAP手机.浏览器.PDA等各种设备来使用各种各样的网络资源(比如应用程序.数据以及这之外的任何网 ...
- 【C#学习笔记】获得本机IP
using System; using System.Net; namespace ConsoleApplication { class Program { static void Main(stri ...