Java IO to get started

Foreword

C language with only a single type FILE * conquer the world different, Java has a stream of family, contains various input / output stream type, the number of over 60! ! ! ! ! !

Before attempting to follow behind CSAPP Proxy Lab to write a C language server, but since I was too dishes, so I wrote with Java ...

But found time to write ... emmmm ... the input and output streams can almost did not put me to pass Gaosi ... pictures do not select the right type of server output stream directly explosion ...

Here Insert Picture Description

So review a wave, I wrote a little summary ...

File encoded with

Before you start talking about IO, first think of nonsense to talk about the old File Java and some coding knowledge related

You can skip XD

File type

Java.io.File class : not related to the specific contents of the file, used to represent files. Involved only basic attributes of a file, path, name, type

The method of constructing objects :

File d = new File("地址字符串");

Ps:Java中路径分割最安全的方法是 File.separator 来代替\\在Windows,比你直接写死了好

Common method

isFile () to determine whether the file
isDirectory () judgment is not a folder is to see is not a directory
getName () to get the name of the file
getParent () to get the parent directory
getPath () Get file full path
length () Gets the size of the file
lastModified () Gets the last modified event
listFiles () returns all subfolders return value is an array class file file []
the delete () delete function
exist (); returns a Boolean to determine the presence of class
d.mkdirs (); create multi-level directory
d. createNewFile (); create the file

Ps:如何在文件不存在的情况下创建目录?

exist() + d.mkdirs() +d.createNewFile()这三个一起配合使用即可

Coding related

Byte and Character

Character: not divided, artificial appreciated, the computer does not know, Eg of: 0 a This is the character
byte: 0 and 1 only know the computer, all binary numbers

字符利于人来阅读,但是不利于计算机阅读

Encoding type

** ASCII code: a byte Byte ** eight small bits to store common English and characters represent up to 256 characters, it is clearly not enough


Spreading code (add byte)

ISO8859 ----- Western European
GBK --------- (the most commonly used more than 20,000 Chinese characters)
GB18030 ---- is GB series represents the most complete coding seventy thousand Chinese characters and character
Big5 - ----------- traditional Chinese

即使这样了但还是不能共通,所以,有了Unicode


** Unicode: ** around the world include all the characters, including the goal of expanding to include global language!
Coding scheme

UTF-8: the ASCII compatible, use of variable-length character, 1-4 small characters stored character letters (such as a, b, c) on one; Chinese characters with a 2.

UTF-16: 2-4 variable length

UTF-32: with four bytes. Anyway, 32bits certainly big enough, but not economic. So UTF-8 is the most commonly used

** ANSI encoding: ** Windows on the default non-Unicode encoding, when the system is simplified Chinese GBK, Traditional Chinese system is Big5. The default is to use Notepad ANSI send each other so you save files in different countries in the region are likely garbled.

IO Overview

In Java IO operations can be classified as follows:

The input and output streams

Is better understood, that is, from the perspective of the program, the files as external, then:

You want the outside world to read content is the Input

To write is to the outside world in Output

Here the outside world can be: file, socket, standard input and output devices (it means the keyboard and screen of the terminal), etc.

Here Insert Picture Description

Character stream and byte stream

Our Input, for example, often see the following two types:

InputStream:

  • Read file in bytes
  • That is, byte []
  • Each unit 8bit, is 1 byte

Here Insert Picture Description
Often media files, such as videos and pictures will be stored in binary form


Reader:

  • Way to read the file character
  • Is char []
  • Each unit 16bit, is two bytes (Java where char is 2 bytes)

Here Insert Picture Description

These are just input, and output series:

Writer

OutputStream

所以:er结尾的就是字符,Stream结尾的就是字节

And packaging Node Class

Node class is a direct channel to establish a program with the outside world:

E.g:

  • To establish a channel between the program and file: FileInputStream fis = new FileInputStream ( "fileName");

But now you can only byte way to read the file contents, and each read one byte file will visit again
Here Insert Picture Description

Packaging is to let you read or write a more convenient time:

For example, you want to read out once a data type (continue with above fis)

  • DataInputStream dis = new DataInputStrream(fis);

Or if you want to read a line of data?

  • BufferedInputStream bis = new BufferedInputStream(bis);

Support layer coated with a layer combination of

This is also reflected in a decorative idea, probably a long way:
Here Insert Picture Description

Node Class

InputStream, OutputStream, Writer, Reader these are abstract classes

Usually to build an IO stream, we need: first node to a stream, then come back a bunch of nesting dolls packaging

But then how will basically use the following methods:

read

read();

Remove the single byte and returns an int. Since it is only the bytes 8bit range 0-255
So when you can not read Chinese characters will flow in bytes. Read the tail -1 is returned
when you output will be like this:

	int c = f.read();
	System.out.println((char)c);

read(buffer);

Create buffer prior to use, that is, byte [] or char [] is then put to the ok after taking a determined size, until the return value is -1

The number of bytes read into the method return value is read how many, but if you read 100 each, and finally only 40, it will repeatedly read 60, read from the reciprocal of 100.

	byte[] buffer = new byte[1024]
	int len = System.in.read(buffer);
	read读的所有IO操作都带着exception的异常处理或者抛出!

Note here that is byte at a time if so read the input stream will come in the carriage length will also read one more than it actually is!

write

flush();

write();

And substantially the same as above, this byte is written

shut down

close();

For external resources, not within the scope of the JVM GC jurisdiction, it is necessary to manually close

Further, the outer package closed, the inner layer will close automatically, for example:

FileInputStream fis =   new FileInputStream("fileName");

BufferedInputStream bis = new BufferedInputStream(bis);


bis.close();

In this case fis also automatically closed. But the real writing time close will throw an error IOException, so it needs try-catch, so much trouble. They actually inherited interface of a AutoCloseable, after JDK1.7, provides a syntactic sugartry-resources

Usage is as follows:

try(
    FileInputStream fis = new FileInputStream("fileName")
   ){
    //....
}

Run automatically closed do not have control

Examples

The contents of a file are written to a file of another process:

    try(
        FileInputStream fis = new FileInputStream("fileName");
        FileInputStream fos = new FileOutputStream("anotherFileName")
       ){

        Integer len = 0;

        byte[] buffer = new byte[1024];

        //循环读入
        while((len = fis.read(buffer))!=-1)
        {
            fos.write(buffer,0,len);
        }   
    }catch(IOException e)
    {
        System.out.println("md出错了!");
    }

Decoration

In the example above we can see that we can only byte (or char) carried out a single operation, and when the actual operation every time a visit from a file, take a byte, this is not too inconvenient it? If we want to each read one line to judge it?

This time, we need to introduce the concept of a wrapper class

Wrapper class can be based on the original flow of operation, the equivalent of filter wrapper class, so we have more ways when in operation, the following are some common

BufferedReader

Buffer What does it mean? buffer!

So, Buffered series is at the same time establishing a buffer stream comes a time when you read and write, the data is put in the buffer, rather than each time to access the device until the buffer is full of when they come to write or read

With BufferedReader for example, the biggest advantage is that he lets you put the string line by line reads:

		FileReader fr = new FileReader("fileName");	
		BufferedReader br = new BufferedReader(fr);

		......
            
            
        String firstLine = br.readLine();

InputStreamReader

You want from your binary file as a string inside to read the content? Possible!

InputStreamReader provides custom coding to help you convert this process interfaces!

Coupled with the BufferedReader!

Use example:

        FileInputStream fis = new FileInputStream("fileName");
        InputStreamReader isr = new InputStreamReader(fis,"utf-8");
		BufferedReader br = new BufferedReader(isr);

Such law-abiding, write up a little trouble, so the actual write:

	BufferedReader br = 
        new BufferedReader(
        new InputStreamReader(
        new FileInputStream("fileName"),"utf-8"));

This is truly sets her play ...


There are many other such DataInputStream, lets you type a data type of a data reading and writing, as well as ZipInputStream, read and write to handle compressed files; there PushBackInputStream this, you can read more on the back of ... basically use Similarly, do not explain.

To be continued ...

Published 33 original articles · won praise 26 · views 2600

Guess you like

Origin blog.csdn.net/qq_43948583/article/details/103529887
Recommended