Java IO processing, javaio

Source: Internet
Author: User

Java IO processing, javaio
File Basics

The name of the abstract path of the file and directory. There are four construction methods.

File (File parent, String child): Creates a File instance from the abstract parent directory.

File (String parent, String child): Creates a File instance from the parent directory.

File (String pathname): Creates a File instance from a specified path.

File (URI path): converts a URI to an abstract path to create a File instance.


ListFiles () method: returns an array of abstract path names, which indicate the Sub-items (files or directories) in the directory)

File file = new File("/home/colin");File[] childs = file.listFiles();

ListFiles (FileFilter filter): FileFilter is a filter of abstract path names and can be used to return subdirectories required by the filter.
File file = new File ("/home/colin"); // have you considered that java does not allow implementation of interface instances, but interfaces are implemented in anonymous internal classes, for example, the FileFilter interface // actually checks the compiled code (you will find that the compiled code contains a class file, which implements this interface and overrides the method of this interface) // This is a virtual instantiation interface, or an indirect instantiation interface. File [] childs = file. listFiles (new FileFilter () {@ Overridepublic boolean accept (File pathname) {return pathname. getName (). startsWith (". ");}});

There is also a listFiles (FilenameFileter filter): FilenameFile is used to detect whether a specified file is contained in a specific directory

Other APIs are relatively simple. You can obtain the File status and create and delete files.


RandomAccessFile: Random file read/write

File instances only involve File operations. java provides random access to files, including read and write operations, which are pointer-based operations.

Two constructor methods:

RandomAccessFile (File name, String model)

RandomAccessFile (String name, String model)

The model specifies the Random Access Mode for files. There are two modes: Read-only mode and read/write mode. "r" indicates that the file access is read-only, "rw" indicates the read and write modes.


RandomAccessFile file = new RandomAccessFile("/home/colin","rw");

Write Data:

Write (byte [] B): write the specified array B to the random read/write File and write it to the pointer location.

Write (byte [] B, int off, int len): Specifies the start position and length.

Write (int n): writes the lower eight bits of n to the file.

It also provides methods for writing specific features: writeBoolean (boolean B), writeInt (int n), writeDouble (double v), writeChart (chart c), writeCharts (String s) writeByte (int n), writeBytes (String s), writeFloat (Float t), etc.

Read data:

Int read (): read 1 byte (8 bits) to put it in the lower eight bits of the int, and the height 24 is 0. If-1 is read, it indicates that the object is read to the end.

Int read (byte [] B): reads a maximum of B. length bytes to the array. The returned value is the actual number of bytes read.

Int read (byte [] B, int off, int length): Specifies the start position and read length of the read array.

There is also the read

ReadBoolean (), readFloat (), and so on. In particular, there is a readLine () reading a row at the current position.

These are all read from the current pointer position

Release associated resources: void close ()

Obtain the pointer of the current RandomAccessFile: long getFilePoint (), in bytes. For example, if an Int is 4 bits

Move the current pointer position: void seek (long pos)

Skip n Bytes: int sikpBytes (int n): returns the actual number of bytes to be skipped. If n is a negative number, no Bytes are skipped.

RandomAccessFile file = null; try {file = new RandomAccessFile ("/home/colin/test.txt", "rw"); // byte [] B = "this is sample RandomAccessFile ". getBytes (); // file. read (B); byte [] B = new byte [10]; while (file. read (B)> 0) {System. out. println (new String (B); System. out. println (file. getFilePointer (); // get the file pointer file. skipBytes (1); // skip one byte for each read} catch (FileNotFoundException e) {e. printStackTrace ();} finally {if (file! = Null) file. close ();}


Basic IO

Input refers to entering the program direction from the outside, that is, when we need to read data, use input.

Output refers to sending data from the program to the outside world. Usually we need to write data to the outside world, so the output is used to write data.

Stream classification

Unit: byte stream (8 bit, image video, etc.) and bytes stream (16 bit, text)

Based on the role: the node stream (directly acting on the stream in the text, directly connected to a specific place (disk, memory) and processing the stream (the stream outside the node stream, it is the connection and encapsulation of an existing stream, and implements data read and write on the encapsulated stream function)

In java, more than 40 streams are derived from four base classes.

Byte streams

Input: InputStream Reader

Output: OutputStream Writer


InputStream and OutputStream

The two are the abstract base classes of byte streams, defining the basic read and write methods, read (), read (byte [] a, int off, int length), read (byte [] B), write (int B), write (byte [] B), write (byte [] B, int off, int len)

Reader and Writer

Both reader and writer are the abstract base classes of the character stream. They define the read and write operations for reading characters. Read (), read (char [] cbuf), read (char [] cbuf, int off, int len), write (char c), write (char [] cbuf), cbuf (cbuf, int off, int len)

File stream

File byte stream:

FileOutputStream can be constructed using the following methods:

FileOUtputStream (File file)

FileOutputStream (String name)

Specifies the file to be written. If the file exists, the content above the file will be cleared.
FileOutputStream (File file, boolean append)

FileOutputStream (String name, boolean append)

If the append parameter is set to true, if the file to be written exists, it is written in the append mode.

FileInputStream can be constructed using the following methods:

FileInputStream (File file)

FileOutputStream (String name)

The file byte stream implements the basic read and write operations of inputStream and outputStream.

NOTE: If-1 is returned during reading, the EOF is read.


Using file streams to copy files:

File file1 = new File ("/home/colin/hello. py "); File file2 = new File ("/home/colin/hello2.py "); FileInputStream input = null; FileOutputStream output = null; try {input = new FileInputStream (file1 ); output = new FileOutputStream (file2); byte [] B = new byte [10]; int len =-1; while (len = input. read (B ))! =-1) {output. write (B, 0, len) ;}} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} finally {try {// first turn off the input stream, then turn off the output stream if (inputput! = Null) inputput. close (); if (output! = Null) output. close () ;}catch (IOException e) {e. printStackTrace ();}}

FileReader and FileWriter are used in the same way as FileInputStream and FileOutputStream.

Buffer stream

BufferedInputStream principle: Buffer byte input stream, internal maintenance of a buffer, the stream will try to read several bytes to the buffer at a time, and then return one by one to know that all the data in the buffer has been read, thus reducing the number of reads, to improve reading efficiency, BIS is a processing stream that provides a buffer function. He also provides the mark, reset, and skip Methods

The following constructor is provided:

BufferedInputStream (InputStream input)

BufferedInputStream (InputStream input, int size): size specifies the buffer size


BufferedOutputStream principle: the buffer output stream maintains a buffer internally. when data is written to the stream, the data is stored in the buffer zone. When the buffer zone is full, the buffer stream writes all the data at one time.

The following constructor is provided:

BufferedOutputStream (OutputStream out)

BufferedOutputStream (OutputStream out, int size): Specifies the buffer size.

BufferedOutputStream only provides the write and flush () methods, flush () clears the buffer, and forcibly writes data in the buffer.


Using a buffer stream for file replication:

BufferedInputStream bis = null; BufferedOutputStream bos = null; try {bis = new BufferedInputStream (new FileInputStream (new File ("/home/colin/hello. py "); bos = new BufferedOutputStream (new FileOutputStream (new File ("/home/colin/hello3.py "); int len =-1; byte [] B = new byte [10]; while (len = bis. read (B ))! =-1) {bos. write (B, 0, len);} bos. flush ();} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} finally {try {// first turn off the input stream, then turn off the output stream if (bis! = Null) bis. close (); if (bos! = Null) bos. close () ;}catch (IOException e) {e. printStackTrace ();}}

BufferedReader and BufferedWriter have the same implementation principle as BufferedInputStream and BufferedOutputStream. However, BufferedWriter provides newLine (), a method object stream for writing line breaks.

Object serialization: Objects exist in the memory. Sometimes you need to save the objects to the disk or transfer the objects. At this time, the object needs to be converted into a byte sequence, which is called object serialization.

Object deserialization: Sometimes the byte sequence needs to be converted into the corresponding object. This process becomes the deserialization of the object.

ObjectOutputStream: the output stream used to serialize objects.

The following constructor is provided:

ObjectOutputStream ()

ObjectOutputStream (OutputStream out)

The write method is used to convert an object into a byte sequence and write it out. The write method provides such methods as writeInt.

ObjectInputStream: Used to deserialize objects.

The following constructor is provided:

ObjectInputstream ()

ObjectInputStream (InputStream input)

Use the readObject () method provided by OSS to read bytes and convert them to corresponding objects.


The overall idea is to transfer the object and convert the object into a byte stream for transmission. Therefore, first write the object through ObjectOutputStream and write it as a byte for transmission. It needs to be read after being passed to the target location. At this time, the transmitted bytes are converted into objects.

If you use ObjectOutputStream for serialized writing, you need to serialize the object to implement the Serializable interface. This interface does not have any method but a serialization flag. Generally, a serialVersionUID is required to implement this interface, indicating the version of this class. If the declared compiler is not displayed, A serialVersionUID is also provided after computation, but different compilers implement different implementations. Therefore, if you want to cross-platform, the declared version number should be displayed. When the class object is serialized to the disk, the demand changes accordingly and the attributes of the class are changed, the deserialization will result in InvalidClassException, which will cause incompatibility problems. However, when the serialVersionUID is the same, different fields are deserialized with the default value of type to avoid incompatibility issues.

Transient keywords: When we serialize an object, the byte sequence is usually large. Sometimes we can ignore unnecessary attributes when serializing an object, to reduce the size of the serialized byte sequence, you can declare it as a transient so that these attributes will be ignored during serialization.

Instance:

/** Construct the Emp class and serialize and deserialize its objects */public class Emp implements Serializable {private static final long serialVersionUID = 1L; private String name; private int age; private double salary; private transient String description; // use the transient modifier to output null public Emp (String name, int age, double salary, String description) {this. name = name; this. age = age; this. salary = salary; this. description = description;} public S Tring getName () {return name;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public void setAge (int age) {this. age = age;} public double getSalary () {return salary;} public void setSalary (double salary) {this. salary = salary;} public String getDescription () {return description;} public void setDescription (String description) {this. description = description;} @ Overr Idepublic String toString () {return "Emp [name =" + name + ", age =" + age + ", salary =" + salary + ", description = "+ description +"] ";}}/** serialize the Emp object and store */public static void testOos () {ObjectOutputStream oos = null; try {FileOutputStream fos = new FileOutputStream (new File ("/home/colin/oos. obj "); oos = new ObjectOutputStream (fos); Emp emp = new Emp (" colin ", 23,130 00," I want you !!! "); Oos. writeObject (emp);} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} finally {try {if (oos! = Null) oos. close ();} catch (IOException e) {e. printStackTrace () ;}}/ ** output the stored Emp object reverse sequence */public static void testOis () {ObjectInputStream ois = null; try {FileInputStream FCM = new FileInputStream (new File ("/home/colin/oos. obj "); ois = new ObjectInputStream (FCM); Emp emp = (Emp) ois. readObject (); System. out. println (emp. getName () + "," + emp. getAge () + "," + emp. getSalary () + "," + emp. getDescription ();} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} catch (ClassNotFoundException e) {e. printStackTrace ();}}



Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.