The use and difference of Java note--file,fileinputstream,filereader,inputstreamreader,bufferedreader

Source: Internet
Author: User
Tags ming

Transferred from: Http://hi.baidu.com/danghj/item/0ef2e2c4ab95af7489ad9e39

Resources:

L "Core Java" chapter 12

L How to manipulate text files using Java http://java.ccidnet.com/art/3737/20041108/523627_1.html

What kind of FileReader is L?   What's the difference with FileInputStream? Http://book.hackbase.com/ask2/ask107572.htm

Self-collation and understanding:
Introduction:

C language only needs a file*, and unlike C, Java has a series of flow types, the number of more than 60. The designer of the class library claims: "There are plenty of reasons to give users the choice of a rich stream type: Doing so can reduce program errors." "For example, in the C language, many people think that" writing output streams to a file in a read-only mode "is a common error. (In fact, this is not common.) )

We think that in the C + + language, the main "tool" for stream interface designers to avoid program errors is a cautious attitude, especially in the Java language. The high complexity of the flow library forces the program designer to be cautious.


1. File class

1.1 File Class Introduction ("Core Java" 638 pages)

The file class encapsulates the ability to manipulate the filesystem of a user's machine.

For example, you can use the file class to get the last modified time movement of files, or to delete and rename files. In other words, the stream class is concerned with the contents of the file, and the file class is concerned about the storage of files on disk.

The main methods of the File class are: GetName (), Getcanonicalfile (), LastModified (), Isderector (), Isfile (), GetPath (), etc.;

1.2 The difference between the File class and the FileInputStream class:

The stream class is concerned with the contents of the file, and the file class is concerned about the storage of files on disk.

File does not belong to the stream, only the path name of a file or directory.

Hint: ("core Java" 639 pages)

If you are working with files or directory names, you should use a file object instead of a string. For example, the Equals method of the file class knows that some filesystem is sensitive to case, and the "/" character at the end of the directory does not matter.

Self-Understanding:

There are several constructors for the FileInputStream class or FileReader class, of which the typical two are:

One uses the File object as a parameter, and the other uses a String object that represents the path as a parameter;

I have always felt that the direct use of the String to specify the path, I do not understand why many people first construct a file object, and now finally understand, "if you work with a file or directory name, you should use the files object, not the string." ”!

2. FileInputStream class

2.1 FileInputStream Class Introduction:

Stream processing in bytes (non-Unicode). The byte sequence is: binary data. Encoding independent, there is no garbled problem.

The main methods of the FileInputStream class are:

Read (), read (byte[] b), read (Byte[],int off,int len), available ();

2.2 The difference between the FileInputStream class and the FileReader class:

The form and parameters of the constructors for two classes are the same, the arguments are File objects, or the String that represents the path, what is the difference between them?

L Readers and writers work only on line based character data, so plain text files. For anything else, you must use Streams.

L JDK5 API:

FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.

FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a fileinputstream.

  

  FileInputStream: read by byte stream;

  FileReader: Converts a file into a stream of characters to read;

  The InputStream provides a byte stream reading, not a text read, which is fundamentally different from the reader class.

Read in reader is a char array or a string, using InputStream to read a byte array.

The reader class and its subclasses provide a stream of characters read char (16-bit, Unicode encoding), and InputStream and its subclasses provide a byte stream reading bytes (8 bits),

So the FileReader class is to read the file as a stream of characters, FileInputStream read the file by byte stream,InputStreamReader can convert the read as stream into a character stream mode, It's a bridge between reader and stream.

Originally Java was not supporting the processing of text files, in order to compensate for this shortcoming introduced the reader and writer two classes.

The FileInputStream class is a binary input/output, I/O speed is fast and efficient, but its read () method reads a byte (binary data), which is not good for people to read.

And the FileReader class compensates for this flaw, can be in text format input/output, very convenient, such as can be used

while ((ch = filereader.read ())!=-1) loops to read the file, you can use the

The BufferedReader ReadLine () method reads the text one line at a row.

When we read and write text files, it is very convenient to use reader, such as FileReader, InputStreamReader and BufferedReader. One of the most important classes is InputStreamReader, which is a bridge that converts bytes into characters. You can specify the encoding in the constructor, and if you do not specify it, the default encoding for the underlying operating system, such as GBK, is used.

FileReader and InputStreamReader involve encoding conversion (specifying encoding or using OS default encoding), which may appear garbled on different platforms! The FileInputStream is processed in binary mode, and there is no garbled phenomenon.

2.3 Self-understanding:

If you are working with plain text files, it is recommended to use FileReader because it is more convenient and more suitable for reading, but be aware of coding problems !

In other cases (processing of non-plain text files), FileInputStream is the only option; FileInputStream is a socket communication use a lot of, such as the way the file stream is stream to the server!


3. FileReader class

3.1 FileReader Class Introduction:

Subclasses of the InputStreamReader class, all methods (read (), etc.) are inherited from the parent class InputStreamReader;

3.2 Differences from the InputStreamReader class:

Self-Understanding:

The main difference between this class and its parent class InputStreamReader is the constructor function, which is mainly the constructor!

from As seen in the InputStreamReader constructor, the parameters are InputStream and encoded, and you can see that when you want to specify the encoding method, The InputStreamReader class must be used;

The parameters of the FileReader constructor are the same as the FileInputStream, which is the File object or A string representing the path, as you can see, when you want to read a file based on a Files object or a string, use FileReader; want to filereader the role of sub-class is the small division of labor it is.

3.3 General Usage:

New FileReader ("Ming.txt"); Char New Char [1024x768]; int ch = 0;  while (ch = fr.read ())!=-1 ) {    System.out.print ((char) ch);}

4. InputStreamReader class

Input/output in text format, you can specify the encoding format;

Main methods: getencoding (), read ();

General usage:

New InputStreamReader (new FileInputStream ("Ming.txt"));  while (ch = isr.read ())!=-1) {System.out.print ((char) ch);}

5. BufferedReader class

  

JDK5 API:

Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

The BufferedReader is extended by the reader class, providing a common buffer-style text read, and providing a very useful readline,

reading the branch text is a good fit , BufferedReader is for reader, not directly for the file, and not just for file reading.

General usage:

New BufferedReader ( new InputStreamReader (new FileInputStream ("Ming.txt"null;  while (data = Br.readline ()) =null) {System.out.println (data);}

6. Summarize the above and draw a good standard usage:

1)    new File ("Hello.txt"); FileInputStreamin =new fileinputstream (file);

2)    new File ("Hello.txt");     FileInputStreamin =new  fileinputstream (file);    InputStreamReader Inreader=new  InputStreamReader (in); BufferedReader Bufreader=new bufferedreader (Inreader);     

3)    new File ("Hello.txt");    FileReader FileReader=new  filereader (file); BufferedReader Bufreader=new bufferedreader (FileReader);

7. Some of the differences in wording:

1new File ("Hello.txt"); FileInputStreamin =new  fileinputstream (file); InputStreamReader inreader=new  InputStreamReader (in); BufferedReader Bufreader=new

2) FileInputStream in=nullnew File ("Hello.txt");in =new  FileInputStream (file); BufferedReader Bufreader=new bufferedreader (new

3new File ("Hello.txt"); BufferedReader Bufreader=new bufferedreader ( new InputStreamReader (new FileInputStream (file));

The minor differences between the two types of notation:
a) in the second way, "FileInputStream in=null;" The definition is placed at the beginning, which indicates that there should be a place to use the In object variable; (BufferedReader)

b) The second method does not define the InputStreamReader object variable, directly in the constructor of BufferedReader new one,
This is the main difference from the first way: The InputStreamReader object is used only once!

This is better for applications that only need to use this InputStreamReader object once, without defining an InputStreamReader object variable, and receiving a reference to the object returned by new. Because this InputStreamReader object variable is not required in the following program, it is not necessary to define it; So in this case, the second way is better than the first.

c) The third Way, a typical three-layer nested delegation relationship, clearly see the delegation mode of reader ("Corejava" in Chapter 12 has a diagram describing the delegation relationship), FileInputStream and InputStreamReader do not define the variable , the objects that are generated by new are used only once.


d) the difference between the three ways is whether the FileInputStream and InputStreamReader objects are used only once, whether they need to define their object variables, and the individual's coding habits.

e) But to be aware of exception handling, FileInputStream (file) throws Notfilefoundexception,

If you use the Surround method (try&catch) processing, should be used in the second way, so that you can use the SYSTEM.OUT.PRINTLN hint file is not found;

Of course, after the function name is used throws Exception, and then the third Way is also OK, but it seems that this is suitable for a user interface situation, the exception thrown in the client processing.

The use and difference of Java note--file,fileinputstream,filereader,inputstreamreader,bufferedreader

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.