Java IO - Reader

前言

JavaIO一共包括两种,一种是stream,一种是reader/writer,每种又包括in/out,所以一共是四种包。Java 流在处理上分为字符流和字节流。字符流处理的单元为 2 个字节的 Unicode 字符,分别操作字符、字符数组或字符串,而字节流处理单元为 1 个字节,操作字节和字节数组。
Java 内用 Unicode 编码存储字符,字符流处理类负责将外部的其他编码的字符流和 java 内 Unicode 字符流之间的转换。而类 InputStreamReader 和 OutputStreamWriter 处理字符流和字节流的转换。字符流(一次可以处理一个缓冲区)一次操作比字节流(一次一个字节)效率高。

0. 目录

  1. Reader
  2. BufferedReader
  3. InputStreamReader
  4. FileReader
  5. 总结

1. Reader

reader
Reader是一个抽象类,其介绍如下:

Abstract class for reading character streams. The only methods that a subclass must implement are read(char[], int, int) and close(). Most subclasses, however, will override some of the methods defined here in order to provide higher efficiency, additional functionality, or both.

1.1 主要方法

abstract void   close()
Closes the stream and releases any system resources associated with it.void    mark(int readAheadLimit)
Marks the present position in the stream.boolean markSupported()
Tells whether this stream supports the mark() operation.int read()
Reads a single character.int read(char[] cbuf)
Reads characters into an array.abstract int    read(char[] cbuf, int off, int len)
Reads characters into a portion of an array.int read(CharBuffer target)
Attempts to read characters into the specified character buffer.boolean ready()
Tells whether this stream is ready to be read.void    reset()
Resets the stream.long    skip(long n)
Skips characters.

注意,不同于stream的是reader读的是char[]。
其常见的子类包括BufferedReader和InputStreamReader,InputStreamReader的子类FileReader也很常见,下面简单介绍一下。

2. BufferedReader

BufferedReader继承Reader,本身的方法非常简单,其官方解释如下:

Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

简单翻译一下:

从流里面读取文本,通过缓存的方式提高效率,读取的内容包括字符、数组和行。
缓存的大小可以指定,也可以用默认的大小。大部分情况下,默认大小就够了。

2.1. 构造函数

BufferedReader有两个构造函数,其声明如下:

BufferedReader(Reader in)
Creates a buffering character-input stream that uses a default-sized input buffer.BufferedReader(Reader in, int sz)
Creates a buffering character-input stream that uses an input bufferof the specified size.

一个是传一个Reader,另外一个增加了缓存的大小。

常见的初始化方法

BufferedReader br = new BufferedReader(new FileReader("d:/123.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

第一个方法是读取一个文件;第二个方法是从标准输入读。

2.2. 主要方法

void    close()
Closes the stream and releases any system resources associated with it.void    mark(int readAheadLimit)
Marks the present position in the stream.boolean markSupported()
Tells whether this stream supports the mark() operation, which it does.int read()
Reads a single character.int read(char[] cbuf, int off, int len)
Reads characters into a portion of an array.String  readLine()
Reads a line of text.boolean ready()
Tells whether this stream is ready to be read.void    reset()
Resets the stream to the most recent mark.long    skip(long n)
Skips characters.

提供了三种读数据的方法read、read(char[] cbuf, int off, int len)、readLine(),其中常用的是readLine。

3. InputStreamReader

InputStreamReader的介绍如下:

An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.
Each invocation of one of an InputStreamReader's read() methods may cause one or more bytes to be read from the underlying byte-input stream. To enable the efficient conversion of bytes to characters, more bytes may be read ahead from the underlying stream than are necessary to satisfy the current read operation.
For top efficiency, consider wrapping an InputStreamReader within a BufferedReader. For example:

 BufferedReader in= new BufferedReader(new InputStreamReader(System.in));

也就是说,InputStreamReader是把字节翻译成字符的。

3.1构造函数

InputStreamReader(InputStream in)
Creates an InputStreamReader that uses the default charset.InputStreamReader(InputStream in, Charset cs)
Creates an InputStreamReader that uses the given charset.InputStreamReader(InputStream in, CharsetDecoder dec)
Creates an InputStreamReader that uses the given charset decoder.InputStreamReader(InputStream in, String charsetName)
Creates an InputStreamReader that uses the named charset.

可以看到,InputStreamReader的构造函数会传入一个字符编码,通常用InputStreamReader来解决乱码问题。

3.2. 主要方法

void    close()
Closes the stream and releases any system resources associated with it.String  getEncoding()
Returns the name of the character encoding being used by this stream.int read()
Reads a single character.int read(char[] cbuf, int offset, int length)
Reads characters into a portion of an array.boolean ready()
Tells whether this stream is ready to be read.

3.3. 示例代码

经常用InputStreamReader解决乱码问题,示例代码如下:

    private void test() throws Throwable {BufferedReader in = null;try {InputStreamReader isr = new InputStreamReader(new FileInputStream("d:/123.txt"), "UTF-8");in = new BufferedReader(isr);while (true) {String lineMsg = in.readLine();if (lineMsg == null || lineMsg.equals("")) {break;}}} catch (Throwable t) {throw t;} finally {try {if (in != null) {in.close();}} catch (Throwable t) {throw t;}}}

编码集见本文末尾。

4. FileReader

其介绍如下:

Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream.
FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a FileInputStream.
FileReader是方便读取字符文件的。

4.1. 构造函数

FileReader(File file)
Creates a new FileReader, given the File to read from.FileReader(FileDescriptor fd)
Creates a new FileReader, given the FileDescriptor to read from.FileReader(String fileName)
Creates a new FileReader, given the name of the file to read from.

可以看到,FileReader的构造函数主要是读取文件。

5. 总结一下:

1. BufferedReader可以更高效的读取文件

2. InputStreamReader可以处理乱码问题

3. FileReader可以直接读取文件,方便

4. 常见编码

  • 7位ASCII字符,也叫作ISO646-US、Unicode字符集的基本拉丁块
    "US-ASCII"
  • ISO 拉丁字母表 No.1,也叫作 ISO-LATIN-1
    "ISO-8859-1"
  • 8 位 UCS 转换格式
    "UTF-8"
  • 16 位 UCS 转换格式,Big Endian(最低地址存放高位字节)字节顺序
    "UTF-16BE"
  • 16 位 UCS 转换格式,Little-endian(最高地址存放低位字节)字节顺序
    "UTF-16LE"
  • 16 位 UCS 转换格式,字节顺序由可选的字节顺序标记来标识
    "UTF-16"
  • 中文超大字符集
    "GBK"

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/350784.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

python程序设计语言的执行方式_编程语言用Python执行程序的4种方式

在编写代码中,经常会遇到在 Python程序中打开外部程序的需求,那么在Python里如何打开外部程序呢?今天我们来介绍四种不同的方式,供大家参考收藏。 使用 os.system() os.system(command)是最简单的一种方式,我们import os模块&…

leetcode 994.腐烂的橘子

题目: 在给定的网格中,每个单元格可以有以下三个值之一: 值 0 代表空单元格;值 1 代表新鲜橘子;值 2 代表腐烂的橘子。每分钟,任何与腐烂的橘子(在 4 个正方向上)相邻的新鲜橘子都会…

运行时异常和检查性异常区别

Java提供了两类主要的异常:runtime exception和checked exception。checked 异常也就是我们经常遇到的IO异常,以及SQL异常都是这种异常。对于这种异常,JAVA编译器强制要求我们必需对出现的这些异常进行catch。所以,面对这种异常不管我们是否愿…

VS2015配置freegult

与vs配置opencv类似 1.首先先找到自己系统里OpenGL相关.h.lib .dll的位置 一般系统里已自带,只要去找到就好,我的位置: gl.h C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\gl OpenGL32.Lib GlU32.Lib C:\Program Files\Microsoft…

java 死锁的检测与修复_调查死锁–第4部分:修复代码

java 死锁的检测与修复在这个简短的博客系列的最后BadTransferOperation中,我一直在讨论分析死锁,我将修复BadTransferOperation代码。 如果您已经看过本系列的其他博客 ,那么您会知道,为了达到这一点,我创建了死锁演示…

python下载url_三种Python下载url并保存文件的代码详解

利用程序自己编写下载文件挺有意思的。 Python中最流行的方法就是通过Http利用urllib或者urllib2模块。 当然你也可以利用ftplib从ftp站点下载文件。此外Python还提供了另外一种方法requests。 来看看三种方法是如何来下载zip文件的: import urllib import urllib2 …

springcloud(七)-Feign声明式REST调用

前言 前面我们使用的RestTemplate实现REST API调用,代码大致如下: public User findById(PathVariable Long id) {return restTemplate.getForObject("http://localhost:8084/" id, User.class);} 由代码可知,我们是使用拼接字符串…

OpenGL 各类库的解析gl glu glut freeglut glfw glew

gl.h gl库是核心库,gl中包含了最基本的3D函数,可以再本地电脑中的: C:\Program Files (x86)\MicrosoftSDKs\Windows\v7.0A\Include\gl 路径下找到gl.h头文件,打开后可以看到其中定义的上百个相关函数。 glu.h glu是实用库&#xf…

Java中throw和throws的区别

系统自动抛出的异常 所有系统定义的编译和运行异常都可以由系统自动抛出,称为标准异常,并且 Java 强烈地要求应用程序进行完整的异常处理,给用户友好的提示,或者修正后使程序继续执行。 语句抛出的异常 用户程序自定义的异常和应…

面试问题:检查牙套

这是较容易的编码任务之一,但是您仍然可以在一些初步的技术筛选中达到要求。 问题看起来像这样: 给定仅包含字符( , ) , { , } , [和]的字符串,请确定输入字符串是否有效。 括号必须以正确的顺…

python字符串长度_如何使用python获取字符串长度?哪些方法?

掌握多种python技巧,对于我们更好的灵活应用python是非常重要的,比如接下来给大家介绍的获取字节长度,那大家脑海里就该有印象了,有几种方法呢?一起来看下吧~1、使用len()函数 这是最直接的方法…

C++内存

在C中,内存分成5个区,他们分别是堆、栈、自由存储区、全局/静态存储区和常量存储区。 栈,就是那些由编译器在需要的时候分配,在不需要的时候自动清楚的变量的存储区。里面的变量通常是局部变量、函数参数等。 堆,就是那…

Dijkstra算法——计算一个点到其他所有点的最短路径的算法

迪杰斯特拉算法百度百科定义:传送门 gh大佬博客:传送门 迪杰斯特拉算法用来计算一个点到其他所有点的最短路径,是一种时间复杂度相对比较优秀的算法 O(n2)(相对于Floyd算法来说) 是一种单源最短…

浅谈java中extends与implements的区别

Extends可以理解为全盘继承了父类的功能。implements可以理解为为这个类附加一些额外的功能;interface定义一些方法,并没有实现,需要implements来实现才可用。extend可以继承一个接口,但仍是一个接口,也需要implements之后才可用。对于class而言,Extends…

注意力机制 神经网络_图注意力网络(GAT)

引言作者借鉴图神经网络中的注意力机制,提出了图注意力神经网络架构,创新点主要包含如下几个:①采用masked self-attention层,②隐式的对邻居节点采用不同权重③介绍了多头注意力机制。 在作者的Introduction中,该论文…

java版问题

1.必填项在初次保存后应该已经有值了,怎么会加载数据又是空的的? 2.客户类型 企业性质? 一般机构、上市公司.... 3.文档管理-->上传文档,如果左侧选中文档节点时,上传文档时是否默认选中文档节点。 转载于:https:/…

html5标签属性大全_HTML5中video标签如何使用

HTML5中的video标签用于播放视频文件的,在video标签中我们可以设置窗口的宽高,视频的自动播放,循环播放以及视频的封面图片等等HTML5是下一代HTML,新增了许多新的标签,这些标签实现了许多新的功能。并且还减少了对外部…

Java中@Override的作用

Override是伪代码,表示重写(当然不写也可以),不过写上有如下好处: 1、可以当注释用,方便阅读; 2、编译器可以给你验证Override下面的方法名是否是你父类中所有的,如果没有则报错。例如,你如果没写Override,而你下面的…

java程序中用户名和密码_在Java应用程序中使用密码术

java程序中用户名和密码这篇文章描述了如何使用Java密码体系结构 (JCA),该体系结构使您可以在应用程序中使用密码服务。 Java密码体系结构服务 JCA提供了许多加密服务,例如消息摘要和签名 。 这些服务可通过特定于服务的API来访…

C++ setw和setfill

在C中&#xff0c;setw(int n)用来控制输出间隔。 例如: cout<<s<<setw(8)<<a<<endl; 则在屏幕显示 s a //s与a之间有7个空格&#xff0c;setw()只对其后面紧跟的输出产生作用&#xff0c;如上例中&#xff0c;表示a共占8个位置&#xff0c;不…