Learning Io flow mechanism of java

IO streams mechanism

Use the File class

File class constructor

File (URI uri)

File(String pathname)

File(File parent, String child)

File(String parent, String child)

File class common method

boolean exists (): determine whether a file exists

boolean createNewFile (): When you create a new file, can only create a file, you can not create directories (folders), create first determine whether the file exists, does not exist, create and returns true, there is false.

Absolute path File file format File getAbsoluteFile () File type, the equivalent of File file = new File (absolute name),

Absolute path string String getAbsolutePath () String type

String getName (): Gets the name of the path is the last stage

String getPath () // get is the name of a relative path: playing something called File object is getPath () method

String Parent () // Returns the parent directory of the current file, if there is no return to the parent directory null

bolean isDirectory () // determine whether the file

bolean isFile () // determine whether it is a folder

bolean delete () // delete a file or folder

File [] listFiles () // only get all the files in the current folder

Long length () // Get the length of the point before the folder

public class Test01_01 {
    public static void main(String[] args) throws IOException {
        // 创建文件对象:绝对路径
        File f1 = new File("d:/a.txt");
        // 创建文件对象:相对路径
        File f2 = new File("a.txt");
        boolean b1 = f1.createNewFile();
        boolean b2 = f2.createNewFile();

        String path1 = f1.getAbsolutePath(); //d:\a.txt
        String path2 =  f2.getAbsolutePath(); //C:\idea_workspace\basic-java\a.txt
        System.out.println(path1+" "+path2);
        File fpath1 = f1.getAbsoluteFile(); //d:\a.txt
        File fpath2 = f2.getAbsoluteFile(); //C:\idea_workspace\basic-java\a.txt
        System.out.println(fpath1+" "+fpath2);

        String name1 = f1.getName(); //a.txt
        String name2 = f2.getName(); //a.txt
        System.out.println(name1+" "+name2);
        /*
        获取的是相对路径
         */
        String  p1 = f1.getPath();//d:\a.txt
        String p2 = f2.getPath(); //d:\a.txt
        System.out.println(p1+" "+p2);
        File f3 = new File("d:/aaa/aa");
        System.out.println(f3.getParent()+"f3....");
        System.out.println(f2.getParent()+"f2....");
        Boolean b = f3.mkdirs();
        System.out.println(b);
        File f4 = new File(f3,"a"); //在 aaa/aa文件夹下再创建一个文件目录a
        String parent = f4.getParent();
        System.out.println(parent);
        f4.mkdir();
        File f5 = new File("d:/aaa/aa/a","a.txt");
        System.out.println(f5.getParent());
        System.out.println(f4.getName()); //a
        f5.createNewFile();//在d:/aaa/aa/a下创建一个a.txt文件
        System.out.println(f5); //d:\aaa\aa\a\a.txt,实际是复写了toStirng()方法,在toStirng中调用了getPath()
        //删除文件或文件夹delete()
        f2.delete();
        f1.delete();

    }


}


    public static void main(String[] args) {
        // 创建文件对象
        File f = new File("d:/aaa/b.txt");
        // 获得文件名
        String filename = f.getName();
        // 获得文件大小
        long filesize = f.length();
        // 获得文件的绝对路径
        String path = f.getAbsolutePath();
        // 获得父文件夹路径,返回字符串
        String parentPath = f.getParent();
        // 获得父文件夹路径,返回文件对象
        File parentFile = f.getParentFile();
        // 输出信息
        System.out.println("文件名:" + filename);
        System.out.println("文件大小:" + filesize);
        System.out.println("文件路径:" + path);
        System.out.println("文件父路径:" + parentPath);
        System.out.println("文件父路径:" + parentFile);
    }

operation result

Determine whether a file or folder

    public static void main(String[] args) {
        // 创建文件对象
        File f1 = new File("d:/b.txt");
        // 判断是否是一个文件
        if(f1.isFile()) {
            System.out.println(f1.getName()+"是一个文件");
        }  else {
            System.out.println(f1.getName()+"不是一个文件");
        }
        // 创建文件对象
        File f2 = new File("d:/aaaa");
        // 判断是否是一个文件夹
        if(f2.isDirectory()) {
            System.out.println(f2.getName()+"是一个文件夹");
        }  else {
            System.out.println(f2.getName()+"不是一个文件夹");
        }
    }

operation result:

Get a list of all files in the current folder

public class Test01_08 {
    public static void main(String[] args) {
        // 创建文件对象
        File f = new File("d:/aaa");
        // 获得文件夹下所有文件
        File[] files = f.listFiles();
        // 遍历文件数组
        for (File file : files) {
            // 将文件的名字打印到控制台
            System.out.println(file.getName());
        }
    }
}

listFiles(FileFilter filter)、File listFiles(FilenameFilter filter)

, ListFile rewrite method

File [] listFiles (FileFilter filter) // Returns the folder satisfy the specified filter criteria files and directories.

File listFiles(FilenameFilter filter)

FileFilter FilenameFilter and is an interface, the interface defines only accept () a method must be used to implement the method of the interface

boolean accept (File pathname): FileFilter method, File pathname of the file File both file types have the type of directory

boolean accept (File dir, String name): FilenameFilter method,

Note: File dir: all files are packaged into a directory

Step File [] file = f.listFile (FileFilter filter) Method:

1. Obtain all files under the folder, all the files are packaged as File type

2. traverse the file acquired FileFilter the call accept (File pathname) method, the incoming file one by one, according to the filter rules file accept () defined in the return value determination method, the method returns true if the current put traversal file files stored in the file [] array `

Note: The principle calls boolean accept (File dir, String name) about the same, but also one more function, the file name of the current folder of files that can be received, String name: name of the file is received, not the path name

public class Test01_09 {
    public static void main(String[] args) {
        File f = new File("d:/aaa/aa/a");
        /**
         *    d:/aaa/aaa/a下有两个文件:一个_a文件夹,一个a.txt文件
         *    要求:只获取d:/aaa/aaa/a下的文件,不获取文件夹
         */
         File[] file = f.listFiles(new FilenameFilter() {
             @Override
             public boolean accept(File pathname, String name) {
                 System.out.println(name); //a.txt /_a
                 if(name.endsWith(".txt")){
                     return true;
                 }
                 return false;
             }
         });
        System.out.println(file[0]);
    }

}

** Note: Use FilenameFilter filter, all files are packaged into a directory that is copy folders

Classification stream

By the flow of points:

  • Input stream: data read from disk into memory
  • Output stream: read data from the memory to the hard disk

By type of read points:

  • Stream of bytes: one byte is read when reading
    the OutputStream: output byte stream
    InputStream: the input byte stream
  • Character stream: a first reading character reading
    Reader: input character stream
    Writer: output byte stream

InputStream&OutPutStram

InputStream: input stream of bytes

FileInputStream:

Read files from the hard disk to the memory contents of the input stream of bytes

Construction method:

FileInputStream(File file)

FileInputStream(String name)

Common methods:

int read () // returns the bytes of data corresponding to -1 when there is no data

int read (byte [] b) // returns the number of bytes is read,

Read a byte to a byte [] array, then the byte [] array contents to the application

int read (byte [] b, int off, int len) // returns the number of bytes is read from the memory

A byte is read, the byte data stored in the array location specified

public class Test03 {
    public static void main(String[] args) throws IOException {
        // 创建字节输入流对象并关联文件
        FileInputStream fis = new FileInputStream("d:/c.txt");
        // 定义变量接收读取的字节
        int len = -1;
        byte[] bytes = new byte[6];
        // 循环从流中读取数据
        while((len = fis.read(bytes))>0) {
            System.out.print(new String(bytes,0,len));
        }
        // 关闭流
        fis.close();
    }
}

Program read process flow:

java program ----- "find jvm virtual machine --------> ----- notice Os operating system" OS from the hard disk to read the file

os get data files ------ "Notice OS operating system -----> ------ find JVM virtual machine" data will be returned to the java program

OutPutStram: byte output stream

FileOutputStream: reading data from memory to the output stream of the hard disk, the read byte by byte, when read, is also output when a byte by byte output

Construction method:

  • FileOutputStream (File file) // create an output stream, the stream associated with the specified output destination
  • FileOutputStream (String name) // create an output stream, the stream associated with the specified output destination
  • FileOutputStream (File file, boolean append) // create an output stream, the stream associated with the specified output destination, and specify whether to add data to the end of the file
    append = true: when the stream object is then associated with the target file, the data added to the original end of the file
    append = false: when the object is then associated with the stream object file, overwriting the original file
  • FileOutputStream (String name, boolean append) // create an output stream, the stream is associated to a specified output destination, and specify whether to add data to the end of the file append = true: add append data to the end of the original file = false: overwrite the original file

Common methods:

  • void write (int b): // a byte written to the specified destination number> = 255, write data is empty
  • void write (byte [] b) // byte array of a data write destination, is written in the form of a byte by byte written to the hard disk
  • void write (byte [] b, int off, int len) of bytes of data written to the array location specified hard disk
  • void close () // close stream objects

    FileOutputStream fos = new FileInputStream("d/a.txt")的语义:

1. First create an output stream object

2. The output of the output stream object point destination address d: /a.txt

fos.write (97) semantics:

Get byte stream object data, it outputs the data to the specified destination document

NOTE: write (97) represents a 97 byte as when writing a file, the file will display table for decoding the encoded data, in a corresponding encoding table 97 is a lowercase

public class Test01 {
    public static void main(String[] args) throws IOException {
        // 1.创建字节输出流FileOutputStream对象并指定文件路径。
        FileOutputStream fos = new FileOutputStream("d:/a.txt");
        // 2.调用字节输出流的write(int byte)方法写出数据
        fos.write(254); //
        byte[] bytes = {97,98};
        fos.write(bytes);
        // 3.关闭流
        fos.close();
    }
}

Wrap file:

public class Test02 {
    public static void main(String[] args) throws IOException {
        // 1.创建字节输出流FileOutputStream对象并指定文件路径,并追加方式
        FileOutputStream fos = new FileOutputStream("d:/c.txt",true);
        // 2.调用字节输出流的write方法写出数据
        // 2.1 要输出的字符串
        String content = "i love java \r\n";
        for (int i = 0; i< 5; i++) {
            fos.write(content.getBytes());
        }
        // 3.关闭流
        fos.close();
    }
}

Program write process flow:

java program ----- "find jvm virtual machine --------> notification Os operating system -----" by the OS to read the file memory

os get data files ------ "Notice OS operating system -----> ------ find JVM virtual machine" to write data to the hard disk

Reader&Writer

Reader: character-input stream

FileReader: character input stream file operations

Construction method:

FileReader(File file)

FileReader(String fileName)

Common methods:

int read()

int read (char [] cbuf) // read data is read by a character, a single character to the underlying turn Byte, therefore, the return value is the number of bytes l

For example: reading good aaahhh,

The return int is 8, a Chinese character occupies 2 bytes

int read(char[] cbuf, int off, int len)

Writer: character-output stream

FileWriter: character output file stream operation

Construction method:

  • FileWriter(File file)
  • FileWriter(String fileName)
  • FileWriter(File file, boolean append)
  • FileWriter(String fileName, boolean append)

Common methods:

  • void write(int c)
  • void write(char[] cbuf)
  • void write(char[] cbuf, int off, int len)
  • void write(String str)
  • void write(String str, int off, int len)
  • void flush () // data buffer memory to the destination file brush
  • FileWriter's write () method implementation mechanism

Preferred, to write the character data into byte data into the memory buffer, a flush () to write data in the buffer to a file, so the received byte or a data file, and then depending on the file encoding the reference table corresponding to the byte code into a corresponding character

The Properties (property set) to be used

Properties of the role:

  • load (InputStream instream): // read the key file to the Properties collection
  • store (OutputStream out, String comments): // Write data set, forming a key file

Properties: it is a dual column set

properties extends hashmap ,hashmap implements map

properties: it is a collection of binding to a unique flow Io

Construction method:

Properties () // default paradigm is <String, String>

Common methods:

String getProperty (String key): // calls the underlying map of the get () method

Object setProperty (String key, String value) // underlying the call put map () method

set stringPropertyNames () // return a list of keys, corresponding to the map keySet () method

void load (InputStream inStream) // read external file key, the key data is placed on the Properties collection, the address key associated to the file InputStream

The read file key in the form of usually a value corresponding to the key, the key is generally used for connection or other connection space =

void load(Reader reader)

void store (OutputStream out, String comments) // Properties read set, the data set has been stored in the form of a key file associated with the path OutputStream

void store(Writer writer, String comments)

public class Test06 {
    public static void main(String[] args) throws IOException {
//1:创建一个空的集合
        Properties prop = new Properties();
//2:读取数据到集合中
        prop.load(new FileInputStream("d:/score.txt"));
//3:遍历集合,获取到每一个key
        Set<String> keys = prop.stringPropertyNames();
//获取到每一个key
        for (String key : keys) {
//4:判断当前的key 是否为 "lisi"
            if ("lisi".equals(key)) {
//把"lisi"的值设置为100
                prop.setProperty(key, "100");
            }
        }
//把集合中所有的信息,重新存储到文件中
        prop.store(new FileOutputStream("d://score.txt"), "haha");
    }

}

Byte stream buffer

Function of the buffer flow

On the object elementary stream to create, for enhancing the efficiency of the elementary stream read and write

Four basic streams:

1. The input stream of bytes

2. The output stream of bytes

3. character input stream

4. A character output stream

BufferedInpuStream: byte buffered input stream

Construction method:

  • BufferedInputStream(InputStream in)
  • BufferedInputStream (InputStream in, int size) // int size: specifies the size of the buffer

Common methods:

Inherited InputStream, there is a common method Inputstream

BufferedInputStream (FileInputStream in) the realization of the principle:

By `BufferedInputStream create a buffer zone, the buffer associated with the stream object, FileInputStream in reading data without frequent travel between the hard disk and memory writes data to the buffer, and finally the one-time write data into memory

public class Test07 {
    public static void main(String[] args) throws IOException {
        // 创建字节输出流FileOutputStream对象并指定文件路径。
        FileOutputStream fos = new FileOutputStream("d:\\c.txt");
        // 利用字节输出流创建高效字节输出流对象
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        // 调用高效字节输出流对象的write(int byte)方法写出一个字节数据
        bos.write(97);
        // 关闭流
        bos.close();
    }
}

BufferedOutputStream: byte buffered output stream

  • Construction method:

BufferedOutputStream(OutputStream out)

BufferedOutputStream (OutputStream out, int size) // int size: specifies the size of the buffer

Common methods:

Inherited OutputStream, there is a common method of Outputstream

BufferedOutputStream (FileOutputStream out) the realization of the principle:

By `BufferedInputStream create a buffer zone, the buffer associated with the stream object, when FileOutputStream out to write data without frequent travel between memory and hard drive, the first to write data into the buffer, the last time the data write to the hard disk of

    public static void main(String[] args) throws IOException {
        // 创建字节输出流FileOutputStream对象并指定文件路径。
        FileOutputStream fos = new FileOutputStream("c:\\e.txt");
        // 利用字节输出流创建高效字节输出流对象
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        // 调用高效字节输出流对象的write(byte[] buff)方法写出一个字节数据
        bos.write("i love java".getBytes());
        // 关闭流
        bos.close();
    }

Character buffer flow

BufferedReader: character input stream buffer

Construction method:

BufferedReader(Reader in)

BufferedReader(Reader in, int sz)

Unique method:

String readLine () // read a line of text

BufferedWriter: character buffer output stream

Construction method:

BufferedWriter(Writer out)

BufferedWriter(Writer out, int sz)

Unique method:

void newLine () // write a line separator, separator system according to identification

Conversion flow

Why use conversion flow:

Because there are different ways for encoding characters, different coding tables corresponding to different coding, encoding and decoding a character that should have one relationship

Kind of encoded code

1.GBK encoding: a character occupies 2 bytes

2.Utf-8 encoding: a character 3 bytes

3.ASCII coding

There will be problems because of the different encoding:

A .txt file on the local computer, default encoding format is a two-byte characters, when IDEA (default encoding is utf-8), the read data, the data from the .txt 3 bytes as one. case character code table to find ultra utf-8 corresponding to this case will be garbled

InputStreamReader: converting an input stream

InputStreamReader extend Reder

Construction method:

InputStreamReader(InputStream in)

InputStreamReader (InputStream in, Charset cs) // specified to read data decoding method

The principle of converting the input stream:

FileInputStream fis = new FileInputStream("a.txt");

InputStreamReader isr = new InputStreamReader(fis,"gbk");

1. Create an object converts the input stream, reading InputStreamReader the form of characters associated with the data source

2.FileInputStream objects into byte character object and specify its decoding mode

public static void main(String[] args) throws IOException{
        // 创建字节输入流对象并关联文件
        FileInputStream fis = new FileInputStream("a.txt");
        // 创建转换输入流对象
        InputStreamReader isr = new InputStreamReader(fis,"gbk");
        // 定义字符数组存放读取的内容
        char[] buffer = newchar[1024];
        // 定义变量接收读取的字符个数
        intlen = -1;
        while((len = isr.read(buffer)) != -1) {
            System.out.print(new String(buffer,0,len));
        }
        // 关闭流
        isr.close();
    }

OutputStreamWriter: converting an output stream

OutputStreamWriter extend Writer

Construction method:

  • OutputStreamWriter(OutputStream out)
  • OutputStreamWriter (OutputStream out, Charset cs) // specify the encoding of the output data

Conversion principle output stream:

FileOutputStream fos = new FileOutputStream("a.txt")

OutputStreamWriter osw = new OutputStreamWriter(fos, "gbk");

1. Create a conversion output stream object, the data format in the memory word to

2. FileOutputStream objects into byte character object and specify its encoding

public static void main(String[] args) throws IOException{
        // 要保存的字符串
        String content = "我爱Java";
        // 创建字节输出流对象
        FileOutputStream fos = new FileOutputStream("a.txt");
        // 创建转换输出流对象
        OutputStreamWriter osw = new OutputStreamWriter(fos, "gbk");
        // 调用方法写出数据
        osw.write(content);
        // 关闭流释放资源
        osw.close();
    }

& Serialization stream flow deserialized

ObjectOutputStream: serialization stream

Serialization: the object into a process stream object

Construction method:

ObjectOutputStream(OutputStream out)

Common methods:

writeObject (Object obj) // write the object obj object associated with the output file stream

Note: To serialize objects, the object corresponding to the class must implement the Serializable interface, otherwise it will throw an exception

ObjectInputStream: deserialized stream

Deserialized: the stream object into an object of process

Construction method:

ObjectInputStream (InputStream in)

Common methods:

The readObject Object () serialized stream object into an InputStream associated package Object Object

The principle deserialization:

When a class implements Serializable interface which will be compiled into class files automatically generates a serialVersionUID (serialized identifier), when an object is serialized, the identifier is also written to the serialization stream is deserialized It is used to find a corresponding identifier of the class files, and thus give the corresponding deserialized

When a class file is modified, at this time will generate a new serialVersionUID (serialized identifier), the original serialized stream generated can not be deserialized into corresponding object, it is necessary to secure one class serialVersionUID (serialized identifier character), otherwise it will throw an exception

A fixed serialVersionUID (serialized identifier) ​​approach:

Declare a variable: private static final Long serialVersionUID = custom value

Note: The value is (transient key) modified static and transient variables can not be serialized

Serialization collection

A plurality of objects stored in a file, objects stored in the collection, the collection serialization and deserialization

step:

1. Define a set of objects stored

2. Add objects to the collection

3. Create a serialized stream

4.writeObject (collection)

Print streams

PrintStream extend OutputStream

Features: only responsible for the output data, is not responsible for reading

Construction method:

PrintStream(File file)

PrintStream(OutputStream out)

PrintStream(String fileName)

Common methods: any type of data can be printed

print (any data can be received)

println (may receive any data)

PrintStream ps = new PrintStream(File f);

ps.print () // default output control section

Use System.setOut (ps): Specifies the output file to a new PrintStream (File f) associated

other

Guess you like

Origin www.cnblogs.com/Auge/p/11372920.html