Assignment for week 10 Lessons Learned

A, Java character stream usage:

字符输入/输出流、字符文件和字符缓冲区的输入/输出流
  • Java byte stream functions very powerful, can handle almost any type of input / output operations directly or indirectly.

1, the character input stream:

  • Reader class is the parent class of all characters in the input stream class that defines a number of methods that are valid for all subclasses.
Reader 类的常用子类如下:
CharArrayReader 类:将字符数组转换为字符输入流,从中读取字符。
StringReader 类:将字符串转换为字符输入流,从中读取字符。
BufferedReader 类:为其他字符输入流提供读缓冲区。
PipedReader 类:连接到一个 PipedWriter。
InputStreamReader 类:将字节输入流转换为字符输入流,可以指定字符编码。
  • The InputStreamclass the same, is also included in the class Reader close(), mark(), skip()and reset()the like.

  • Reader class read()method

Method name and return value type Explanation
int read() Reads a character from the input stream and converts it to an integer of 0 to 65535. Return -1 it indicates that has come to the end of the input stream. In order to improve the efficiency of I / O operations, we recommended to make use of two read () method
int read(char[] cbuf) A plurality of characters read from the input stream, and save them to the parameter cbuf specified character array. The method returns the number of characters read, return -1 indicates the end of the input stream has reached the
int read(char[] cbuf,int off,int len) A plurality of characters read from the input stream, and save them to the parameter cbuf specified character array. Wherein, off specify a starting index start saving data in a character array, len specify the number of characters read. The method returns the number of characters actually read, it will return -1, then the input has reached the end of the stream

2, the output character stream

  • In contrast with the Reader class, Writerclass is the parent class of all characters in the output stream, the class has many methods that all subclasses inherit this class are valid.
Writer 类的常用子类如下。
CharArrayWriter 类:向内存缓冲区的字符数组写数据。
StringWriter 类:向内存缓冲区的字符串(StringBuffer)写数据。
BufferedWriter 类:为其他字符输出流提供写缓冲区。
PipedWriter 类:连接到一个 PipedReader。
OutputStreamReader 类:将字节输出流转换为字符输出流,可以指定字符编码。
  • The OutputStreamsame as classes, Writerclass also contains close(), flush()other methods that can refer to the OutputStreammethods of the class.

  • Writer class write()methods and append()methods

Method name and return value type Explanation
void write(int c) Writing a character to the output stream
void write(char[] cbuf) All the characters in the parameter cbuf specified character array written to the output stream
void write(char[] cbuf,int off,int len) The parameter cbuf specified character array several characters written to the output stream. Wherein the specified character array off the starting index, len denotes the number of elements
void write(String str) Write a string to the output stream,
void write(String str, int off,int len) Writing a portion of the character string to the output stream. Wherein the starting offset off in the specified string, len denotes the number of characters
append(char c) Add the parameter c specifies the character to the output stream
append(charSequence esq) Esq add parameters specified character sequence to the output stream
append(charSequence esq,int start,int end) Add the sequence parameter esq specified character sequence to the output stream. Wherein the index of the first character of the subsequence start, end subsequence index of the last character after character, that is to say the content of the sub-sequence comprises a start character index, but the index of the end character is not included
  • Note: All methods Writer classes will lead to an error in the case of IOExceptionanomalies. After closing a flow, then no further action will produce an error.

3, character file input stream

  • In order to facilitate reading, Java provides a convenient --FileReader class for reading character files. There are two class constructor overloads follows.
FileReader(File file):在给定要读取数据的文件的情况下创建一个新的 FileReader 对象。其中,file 表示要从中读取数据的文件。
FileReader(String fileName):在给定从中读取数据的文件名的情况下创建一个新 FileReader 对象。其中,fileName 表示要从中读取数据的文件的名称,表示的是一个文件的完整路径。
  • Creating a class constructor FileReaderwhen the object to be read, and the default character encoding by the byte-buffer size are set by the system. To specify these values yourself, you are in FilelnputStreama structurally InputStreamReader.

  • Note: Creating FileReaderan object may throw a FileNotFoundExceptionexception, so need to use the try catchstatement to catch the exception.

  • The procedure is identical character stream and byte stream, or the stream is first input to create an output stream object, i.e., a connection pipe, establishing a read or write operation is complete, and finally closes the input / output flow channels.
    Example 1
    To E: \ content myjava \ HelloJava.java file is read and output to the console, using the code that implements the class FileReader follows:

package ch13;
import java.io.FileReader;
import java.io.IOException;
public class Test12
{
    public static void main(String[] args)
    {
        FileReader fr=null;
        try
        {
            fr=new FileReader("E:/java/HelloJava.java");    //创建FileReader对象
            int i=0;
            System.out.println("E:\\java\\HelloJava.java文件内容如下:");
            while((i=fr.read())!=-1)
            {    //循环读取
                System.out.print((char) i);    //将读取的内容强制转换为char类型
            }
        }
        catch(Exception e)
        {
            System.out.print(e);
        }
        finally
        {
            try
            {
                fr.close();    //关闭对象
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}
  • As the above code, first create a FileReadercharacter input stream objects fr, the object points to E: \ java \ HelloJava.java file, then call defines the variable i to receive read()the return value, i.e., characters read. In the whileloop, reads one character assigned to integer variables i, the loop is exited read until the end of the file (the input stream when the end of the file is read, it returns a value of -1).

4, character file output stream

  • Java provides a convenient class --FileWriter writing character files, the class constructor has the following four overloads.
FileWriter(File file):在指定 File 对象的情况下构造一个 FileWriter 对象。其中,file 表示要写入数据的 File 对象。
FileWriter(File file,boolean append):在指定 File 对象的情况下构造一个 FileWriter 对象,如果 append 的值为 true,则将字节写入文件末尾,而不是写入文件开始处。
FileWriter(String fileName):在指定文件名的情况下构造一个 FileWriter 对象。其中,fileName 表示要写入字符的文件名,表示的是完整路径。
FileWriter(String fileName,boolean append):在指定文件名以及要写入文件的位置的情况下构造 FileWriter 对象。其中,append 是一个 boolean 值,如果为 true,则将数据写入文件末尾,而不是文件开始处。
  • Creating FileWriteran object, the default character encoding and the default byte-buffer size are set by the system. To specify these values yourself, you can FileOutputStreamconstruct one OutputStream Writerobject.

  • FileWriterCreate a class does not depend on the presence or absence of a file, if the associated file does not exist, it will automatically generate a new file. Before you create a file FileWriterwill open it when you create the object as output. If you attempt to open a read-only file, it will raise an IOExceptionexception.

  • : In the creation FileWritermay lead to an object IOExceptionor SecurityExceptionabnormal, you need to use the try catchstatement to catch the exception.
    Example 2
    preparation of a program, will save the user entered string 4 to E: \ myjava \ book.txt file. As used herein, FileWriterthe class write()method loops to write data to the specified file, the codes are as follows:

package ch13;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Test13
{
    public static void main(String[] args)
    {
        Scanner input=new Scanner(System.in);
        FileWriter fw=null;
        try
        {
            fw=new FileWriter("E:\\java\\book.txt");    //创建FileWriter对象
            for(int i=0;i<4;i++)
            {
                System.out.println("请输入第"+(i+1)+"个字符串:");
                String name=input.next();    //读取输入的名称
                fw.write(name+"\r\n");    //循环写入文件
            }
            System.out.println("录入完成!");
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
        finally
        {
            try
            {
                fw.close();    //关闭对象
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}
  • As described above the code first creates an E: \ is character file java \ book.txt file output stream object fw, and then use forthe cycle entry four strings, calling write()a method to write the string to the specified file. Finally, finallyclose the file statement character output stream.

  • Run the program, according to prompts four strings, as shown below. Then open the E: \ java \ book.txt file, you will see the written content.
请输入第1个字符串:
热点要闻
请输入第2个字符串:
个性推荐
请输入第3个字符串:
热搜新闻词
请输入第4个字符串:
本地看点
录入完成!

5, character buffer input stream

  • BufferedReader principal input stream to assist other characters, it is with a buffer, can first batch of data into memory buffers. The next reading operation can obtain data directly from the buffer, each time without the need to read data from a data source and character encoding conversion so that it can improve the efficiency of data reading.
BufferedReader 类的构造方法有如下两种重载形式。
BufferedReader(Reader in):创建一个 BufferedReader 来修饰参数 in 指定的字符输入流。
BufferedReader(Reader in,int size):创建一个 BufferedReader 来修饰参数 in 指定的字符输入流,参数 size 则用于指定缓冲区的大小,单位为字符。
  • In addition to providing the buffer is other than a character input stream, the BufferedReader also provides the readLine () method returns a string that contains the contents of the line, but does not contain any string terminator, if the end of the stream is null. the readLine () method of each line of text represents the content reading, when faced with 换行(\n), 回车(\r)or directly after the transport newline tag followed by a line can be considered terminated.
    Example 3
    using the readLine BufferedReader class () method read line by line E: \ content java \ Book.txt file, and content read in the console printout, as follows:
package ch13;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Test13
{
    public static void main(String[] args)
    {
        FileReader fr=null;
        BufferedReader br=null;
        try
        {
            fr=new FileReader("E:\\java\\book.txt");    //创建 FileReader 对象
            br=new BufferedReader(fr);    //创建 BufferedReader 对象
            System.out.println("E:\\java\\book.txt 文件中的内容如下:");
            String strLine="";
            while((strLine=br.readLine())!=null)
            {    //循环读取每行数据
                System.out.println(strLine);
            }
        }
        catch(FileNotFoundException e1)
        {
            e1.printStackTrace();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                fr.close();    //关闭 FileReader 对象
                br.close();
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}
  • As the above code, we were first created the name for the object and the name of the FileReader fr is BufferedReader br objects, and then call readLine BufferedReader object (the contents of the file read line by line method). If the contents of the file read is Null, that is, to the end of the file shows that have been read, then exit the loop no longer read operation. Finally, the file input stream of characters and character buffered input stream is closed.

  • Run the program, the output results are as follows:
E:\java\book.txt 文件中的内容如下:
热点要闻
个性推荐
热搜新闻词
本地看点

6, the output character buffer stream

  • BufferedWriter class mainly used to assist other characters output stream, with the same buffer, the first batch of data can be written to the buffer, when the buffer is full, then data is written to the buffer disposable character output stream, its purpose is to improve the efficiency of data write.
BufferedWriter 类的构造方法有如下两种重载形式。
BuflferedWriter(Writer out):创建一个 BufferedWriter 来修饰参数 out 指定的字符输出流。
BufferedWriter(Writer out,int size):创建一个 BufferedWriter 来修饰参数 out 指定的字符输出流,参数 size 则用于指定缓冲区的大小,单位为字符。
  • Such a buffer may be provided in addition to the output character stream, but also provides a new method --newLine (), the method for writing a line separator. Line separator string is defined by the system property line.separator, and not necessarily a single row (\ n) character.

  • Tip: Use the class FileWriter class BufferedWriter same will not be repeated here.

Two, Java byte-stream use:

字节输入/输出流、文件输入/输出流、字节数组输入/输出流

1, input stream of bytes:

  • InputStream class and its subclasses the object represents an input stream of bytes.
InputStream 类的常用子类如下。
ByteArrayInputStream 类:将字节数组转换为字节输入流,从中读取字节。
FileInputStream 类:从文件中读取数据。
PipedInputStream 类:连接到一个 PipedOutputStream(管道输出流)。
SequenceInputStream 类:将多个字节输入流串联成一个字节输入流。
ObjectInputStream 类:将对象反序列化。
  • InputStream class using one or a batch method may read bytes from the stream.
Method name and return value type Explanation
int read() A stream read from the input 8-bit bytes, and converts it to an integer of 0 to 255, and finally returns the integer. Return -1 it indicates that has come to the end of the input stream. In order to improve the efficiency of I / O operations, we recommended to use the read () method of the other two forms
int read(byte[] b) Several bytes read from the input stream, and save them to the parameter b specifies a byte array. The method returns the number of bytes read. Return -1 indicates the end of the input stream has reached the
int read(byte[] b, int off, int len) Several bytes read from the input stream, and save them to the parameter b specifies a byte array. Wherein, off starts saving the designated starting index data in the byte array; len specify the number of bytes read. The method returns the number of bytes actually read. Return -1 indicates the end of the input stream has reached the
void close() Closes the input stream. After the read operation is complete, you should turn off the input stream, the system will release relevant to this input stream resources. Note, InputStream class itself close () method does not do anything, but many of its subclass overrides the close () method
int available() Returns the number of bytes that can be read from the input stream
long skip(long n) Skip parameter n specifies the number of bytes from the input stream. The method returns the number of bytes to skip
void mark(int readLimit) Start flag is set at the current position of the input stream, readLimit parameter specifies the maximum number of bytes is set labeled
boolean markSupported() Determines whether the current flag is set to allow the input stream, it returns true, false otherwise
void reset() The input stream pointer to the start of the return flag is set to

2, the output byte stream

  • Object OutputStream class and its subclasses represents an output stream of bytes. Common subclass of OutputStream follows.
ByteArrayOutputStream 类:向内存缓冲区的字节数组中写数据。
FileOutputStream 类:向文件中写数据。
PipedOutputStream 类:连接到一个 PipedlntputStream(管道输入流)。
ObjectOutputStream 类:将对象序列化。
  • Using OutputStream class or method can be written to a number of bytes from the stream.

3, the byte array input stream

  • ByteArrayInputStream class data can be read from the byte array in memory, the following two class constructor overloads.
ByteArrayInputStream(byte[] buf):创建一个字节数组输入流,字节数组类型的数据源由参数 buf 指定。
ByteArrayInputStream(byte[] buf,int offse,int length):创建一个字节数组输入流,其中,参数 buf 指定字节数组类型的数据源,offset 指定在数组中开始读取数据的起始下标位置,length 指定读取的元素个数。

4, ByteArrayOutputStream

  • ByteArrayOutputStream class can write to the byte array in memory, there are two class constructor overloads it follows.
ByteArrayOutputStream():创建一个字节数组输出流,输出流缓冲区的初始容量大小为 32 字节。
ByteArrayOutputStream(int size):创建一个字节数组输出流,输出流缓冲区的初始容量大小由参数 size 指定。
  • In addition to the class ByteArrayOutputStream output stream of bytes common methods described in the foregoing, two other methods are as follows.
intsize():返回缓冲区中的当前字节数。
byte[] toByteArray():以字节数组的形式返回输出流中的当前内容。

5, file input stream

  • Java FileInputStream stream is commonly used as a comparison, which retrieves input bytes from a file in the file system. FileInputStream can be accessed by using a byte file, a group of bytes or the entire file.
    When you create an object FileInputStream class, if you can not find the file specified will throw FileNotFoundException exception, which must be captured or throw statement.

  • FileInputStream conventional construction methods are mainly the following two overloaded forms.
FileInputStream(File file):通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的 File 对象 file 指定。
FileInputStream(String name):通过打开一个到实际文件的链接来创建一个 FileInputStream,该文件通过文件系统中的路径名 name 指定。
  • The following example demonstrates the FileInputStream (two constructor).
try
{
    //以File对象作为参数创建FileInputStream对象
    FileInputStream fis1=new FiieInputStream(new File("F:/mxl.txt"));
    //以字符串值作为参数创建FilelnputStream对象
    FileInputStream fis2=new FileInputStream("F:/mxl.txt");
}
catch(FileNotFoundException e)
{
    System.out.println("指定的文件找不到!");
}
  • Embodiment, there is assumed a E: \ myjava \ HelloJava.java file, using the following FileInputStream class reading and outputting the contents of the file. Specific code as follows:
package ch13;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class Test10
{
    public static void main(String[] args)
    {
        File f=new File("E:/myjava/HelloJava.java");
        FileInputStream fis=null;
        try
        {
            //因为File没有读写的能力,所以需要有个InputStream
            fis=new FileInputStream(f);
            //定义一个字节数组
            byte[] bytes=new byte[1024];
            int n=0;    //得到实际读取到的字节数
            System.out.println("E:\\myjava\\HelloJava.java文件内容如下:");
            //循环读取
            while((n=fis.read(bytes))!=-1)
            {
                String s=new String(bytes,0,n);    //将数组中从下标0到n的内容给s
                System.out.println(s);
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                fis.close();
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}

如上述代码,在 FileInputDemo 类的 main() 方法中首先创建了一个 File 对象 f,该对象指向 E:\myjava\HelloJava.java 文件。接着使用 FileInputStream 类的构造方法创建了一个 FileInputStream 对象 fis,并声明一个长度为 1024 的 byte 类型的数组,然后使用 FileInputStream 类中的 read() 方法将 HelloJava.java 文件中的数据读取到字节数组 bytes 中,并输出该数据。最后在 finally 语句中关闭 FileInputStream 输入流。

  • ,如下所示的是运行程序后的输出内容。
D:\myjava\HelloJava.java文件内容如下:
/*
*第一个Java程序
*/
public class HelloJava{
    //这里是程序入口
    public static void main(String[] args){
        //输出字符串
        System.out.println("你好 Java");
    }
}

三、Java RandomAccessFile类:

动态读取文件内容
  • 所谓动态读取是指从文件的任意位置开始访问文件,而不是必须从文件开始位置读取到文件末尾。动态读取需要用到 Java 中的 RandomAccessFile 类,该类中有一个文件指针用于标识当前流的读写位置,这个指针可以向前或者向后移动。

  • RandomAccessFile 类的构造方法有如下两种重载形式。
RandomAccessFile(File file,String mode):访问参数 file 指定的文件,访问形式由参数 mode 指定,mode 参数有两个常用的可选值r和rw,其中r表示只读,rw表示读写。
RandomAccessFile(String name,String mode):访问参数 name 指定的文件,mode 参数的含义同上。
  • RandomAccessFile类中还提供了一系列读取和写入数据的方法,表 1 列举了其中一些 常用方法。
    RandomAccessFile类的常用方法
方法名及返回值类型 说明
boolean readBoolean() 从文件中读取一个 boolean 值
byte readByte() 从文件中读取一个带符号位的字节
char readChar() 从文件中读取一个字符
int readlnt() 从文件中读取一个带符号位的整数
long readLong() 从文件中读取一个带符号位的 long 值
String readLine() 从文件中读取下一行文本
void seek(long pos) 指定从文件起始位置开始的指针偏移量
void writeBoolean(boolean v) 以字节的形式向文件中写入一个 boolean 值
void writeByte(int v) 以单字节的形式向文件中写入一个 byte 值
void writeChar(int v) 以双字节的形式向文件中写入一个 char 值
void writelnt(int v) 以4字节的形式向文件中写入一个整数
writeLong(long v) 以8字节的形式向文件中写入一个 long 值
void writeBytes(String s) 以字节序列的形式向文件中写入一个字符串
void skipBytes(int n) 以当前文件指针位置为起始点,跳过 n 字节

四、Java流的概念:

1、输入流

  • Java 流功能相关的类都封装在 java.io 包中,而且每个数据流都是一个对象。所有输入流类都是 InputStream 抽象类(字节输入流)和 Reader 抽象类(字符输入流)的子类。其中 InputStream 类是字节输入流的抽象类,是所有字节输入流的父类。

2、输出流

  • 在 Java 中所有输出流类都是 OutputStream 抽象类(字节输出流)和 Writer 抽象类(字符输出流)的子类。其中 OutputStream 类是字节输出流的抽象类,是所有字节输出流的父类。

Guess you like

Origin www.cnblogs.com/youlanghua/p/11779553.html