Java-I/O学习(7)

Java-I/O学习(7)

Reader

在Java API中,Java Reader类(java.io.Reader)是所有Reader的基类。Reader和InputStream不同的地方在于它是基于字符流的而不是字节流。换句话说,Reader是用来读取文本的数据的,而InputStream是用来读取原始的字节的。

构造函数


//Creates a new character-stream reader whose critical sections will synchronize on the reader itself.
protected Reader()


//Creates a new character-stream reader whose critical sections will synchronize on the given object.
protected Reader​(Object lock)

read


//Attempts to read characters into the specified character buffer. The buffer is used as a repository of characters as-is: the only changes made are the results of a put operation. No flipping or rewinding of the buffer is performed.

//Parameters:
//target - the buffer to read characters into

//Returns:
//The number of characters added to the buffer, or -1 if this source of characters is at its end
int read​(CharBuffer target)


//Reads a single character. This method will block until a character is available, an I/O error occurs, or the end of the stream is reached.

//Returns:
//The character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached
int read()

//Reads characters into an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.

//Returns:
//The number of characters read, or -1 if the end of the stream has been reached
int read​(char[] cbuf)

Writer

在Java API中,Java Writer类(java.io.Writer)是所有Writer的基类。Writer和OutputStream 不同的地方在于它是基于字符流的而不是字节流。换句话说,Writer是用来写文本的数据的,而OutputStream 是用来写原始的字节的。

构造函数


//Creates a new character-stream writer whose critical sections will synchronize on the writer itself.
protected Writer()

//Creates a new character-stream writer whose critical sections will synchronize on the given object.
protected Writer​(Object lock)

write


//Writes a single character. The character to be written is contained in the 16 low-order bits of the given integer value; the 16 high-order bits are ignored.
//Subclasses that intend to support efficient single-character output should override this method.
void write​(int c)

//Writes an array of characters.
void write​(char[] cbuf)


//Writes a portion of an array of characters.
abstract void write​(char[] cbuf,int off,int len)


//Writes a string.
void write​(String str)

InputStreamReader

API文档说明:InputStreamReader类是从字节流到字符流的桥接器:它使用指定的字符集读取字节并将它们解码为字符。 它使用的字符集可以通过名称指定,也可以明确指定,或者可以接受平台的默认字符集。每次调用一个InputStreamReader的read()方法都可能导致从底层字节输入流中读取一个或多个字节。 为了实现字节到字符的有效转换,可以从基础流中提取比满足当前读取操作所需的更多字节。为了获得最高效率,请考虑在BufferedReader中包装InputStreamReader

官网文档:


//For top efficiency, consider wrapping an InputStreamReader within a BufferedReader. For example:

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

构造函数


//Creates an InputStreamReader that uses the default charset.
InputStreamReader​(InputStream in)


//Creates an InputStreamReader that uses the named charset.
InputStreamReader​(InputStream in,String charsetName)


//Creates an InputStreamReader that uses the given charset.
InputStreamReader​(InputStream in,Charset cs)


//Creates an InputStreamReader that uses the given charset decoder.
InputStreamReader​(InputStream in,CharsetDecoder dec)

方法列表



//Reads a single character.

//Returns:
//The character read, or -1 if the end of the stream has been reached
int read()

//Reads characters into a portion of an array.

//Returns:
//The number of characters read, or -1 if the end of the stream has been reached
int read​(char[] cbuf,int offset,int length)


//Returns the name of the character encoding being used by this stream.
//If the encoding has an historical name then that name is returned; otherwise the encoding's canonical name is returned.

//If this instance was created with the InputStreamReader(InputStream, String) constructor then the returned name, being unique for the encoding, may differ from the name passed to the constructor. This method will return null if the stream has been closed.

//Returns:
//The historical name of this encoding, or null if the stream has been closed
String getEncoding()

public static void main(String[] args) throws IOException {

        FileInputStream file = new FileInputStream("E:\\learn-java\\Learning-Java\\MyNotes\\better_write\\Java_IO\\f.txt");

        InputStreamReader reader = new InputStreamReader(file);

        System.out.println(reader.getEncoding());//UTF8

        int data = 0;

        while ( (data = reader.read()) != -1) {

            System.out.println((char) data);
        }

        reader.close();
    }


OutputStreamWriter

API说明:OutputStreamWriter是从字符流到字节流的桥接:使用指定的字符集将写入其中的字符编码为字节。它使用的字符集可以通过名称指定,也可以明确指定,或者可以接受平台的默认字符集。

每次调用write()方法都会导致在给定字符上调用编码转换器。生成的字节在写入底层输出流之前在缓冲区中累积。可以指定此缓冲区的大小,但默认情况下,它足够大,可用于大多数用途。请注意,传递给write()方法的字符不会被缓冲。

为了获得最高效率,请考虑在BufferedWriter中包装OutputStreamWriter,以避免频繁的转换器调用

文档说明:


//For top efficiency, consider wrapping an OutputStreamWriter within a BufferedWriter so as to avoid frequent converter invocations. For example:

Writer out = new BufferedWriter(new OutputStreamWriter(System.out));

构造函数


//Creates an OutputStreamWriter that uses the named charset.

//Parameters:
//out - An OutputStream
//charsetName - The name of a supported charset
OutputStreamWriter​(OutputStream out,String charsetName)

//Creates an OutputStreamWriter that uses the default character encoding.
OutputStreamWriter​(OutputStream out)

//Creates an OutputStreamWriter that uses the given charset.
OutputStreamWriter​(OutputStream out,Charset cs)


//Creates an OutputStreamWriter that uses the given charset encoder.
OutputStreamWriter​(OutputStream out,CharsetEncoder enc)

方法列表


//Writes a single character.
//Parameters:
//c - int specifying a character to be written
void write​(int c)

//Writes a portion of an array of characters.
void write​(char[] cbuf,int off,int len)

//Writes a portion of a string.
void write​(String str,int off,int len)

//Returns the name of the character encoding being used by this stream.
//If the encoding has an historical name then that name is returned; otherwise the encoding's canonical name is returned.
//If this instance was created with the OutputStreamWriter(OutputStream, String) constructor then the returned name, being unique for the encoding, may differ from the name passed to the constructor. This method may return null if the stream has been closed.
String getEncoding()

    public static void main(String[] args) throws IOException {

        FileOutputStream file = new FileOutputStream("E:\\learn-java\\Learning-Java\\MyNotes\\better_write\\Java_IO\\f.txt");

        OutputStreamWriter writer = new OutputStreamWriter(file);

        writer.write(10);

        writer.write("where are you from");

        writer.close();


    }

BufferedReader

BufferedReader类从字符输入流中读取文本并缓冲字符,以便有效地读取字符,数组和行
可以通过构造函数指定缓冲区大小也可以使用默认大小。对于大多数用途,默认值足够大
由Reader构成的每个读取请求都会导致相应的读取请求由基础字符或字节流构成,建议通过BufferedReader包装Reader的实例类以提高效率如


BufferedReader in = new BufferedReader(new FileReader("foo.in"));
 

创建


//Creates a buffering character-input stream that uses a default-sized input buffer.
BufferedReader​(Reader in)

//Creates a buffering character-input stream that uses an input buffer of the specified size.
BufferedReader​(Reader in,int sz)

方法列表


//Reads a single character.

//Returns:
//The character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached
int read()


//Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), a carriage return followed immediately by a line feed, or by reaching the end-of-file (EOF).

//Returns:
//A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached without reading any characters
String readLine()

//Returns a Stream, the elements of which are lines read from this BufferedReader. The Stream is lazily populated, i.e., read only occurs during the terminal stream operation.
//The reader must not be operated on during the execution of the terminal stream operation. Otherwise, the result of the terminal stream operation is undefined.

//After execution of the terminal stream operation there are no guarantees that the reader will be at a specific position from which to read the next character or line.

//If an IOException is thrown when accessing the underlying BufferedReader, it is wrapped in an UncheckedIOException which will be thrown from the Stream method that caused the read to take place. This method will return a Stream if invoked on a BufferedReader that is closed. Any operation on that stream that requires reading from the BufferedReader after it is closed, will cause an UncheckedIOException to be thrown.
Stream<String> lines()


  public static void main(String[] args) throws IOException {
        
        FileReader fileReader = new FileReader(new File("E:\\learn-java\\Learning-Java\\MyNotes\\better_write\\Java_IO\\c.txt"));

        BufferedReader reader = new BufferedReader(fileReader);

        String data = null;

        while ((data = reader.readLine()) != null) {

            System.out.println(data);

        }
        
        reader.close();

    }

BufferedWriter

BufferedWriter 是缓冲字符输出流。它继承于Writer。BufferedWriter 的作用是为其他字符输出流添加一些缓冲功能。BufferedWriter通过字符数组来缓冲数据,当缓冲区满或者用户调用flush()函数时,它就会将缓冲区的数据写入到输出流中。

JDK文档:


//In general, a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters. For example,
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
 


构造函数


//Creates a buffered character-output stream that uses a default-sized output buffer.
BufferedWriter​(Writer out)


//Creates a new buffered character-output stream that uses an output buffer of the given size.

//Parameters:
//out - A Writer
//sz - Output-buffer size, a positive integer
BufferedWriter​(Writer out,int sz)

方法列表


//Writes a line separator. The line separator string is defined by the system property line.separator, and is not necessarily a single newline ('\n') character.
void newLine()

//Writes a single character.
void write​(int c)


//Writes a portion of a String.
void write​(String s,int off,int len)

 public static void main(String[] args) throws IOException {

        FileWriter fileWriter = new FileWriter("E:\\learn-java\\Learning-Java\\MyNotes\\better_write\\Java_IO\\m.txt");

        BufferedWriter writer = new BufferedWriter(fileWriter);

        writer.write(100);

        writer.write("Hello John");

        writer.newLine();

        writer.write("4545");
        writer.close();

    }



CharArrayReader & CharArrayWriter

CharArrayReader 是字符数组输入流。它和ByteArrayInputStream类似,只不ByteArrayInputStream是字节数组输入流,而CharArray是字符数组输入流。CharArrayReader 是用于读取字符数组,它继承于Reader。操作的数据是以字符为单位

CharArrayWriter 用于写入数据符,它继承于Writer。操作的数据是以字符为单位!

各自构造函数

//Creates a CharArrayReader from the specified array of chars.

//Parameters:
//buf - Input buffer (not copied)
CharArrayReader​(char[] buf)

//Creates a CharArrayReader from the specified array of chars.
//The resulting reader will start reading at the given offset. The total number of char values that can be read from this reader will be either length or buf.length-offset, whichever is smaller.
CharArrayReader​(char[] buf,int offset,int length)
//Creates a new CharArrayWriter.
CharArrayWriter()

//Creates a new CharArrayWriter with the specified initial size.

//Parameters:
//initialSize - an int specifying the initial buffer size.
CharArrayWriter​(int initialSize)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值