Java-io input and output stream

Source: Internet
Author: User
Tags object object

First, the encoding of the file

when developing, be sure to note the project's default encoding!!!!!!!! you must remember to close!!!!!!!! when you are working on files. ASCII: US standard Information Interchange code, with a byte of 7 bits can represent one character iso8859-1: Latin Code table, Western European standard character set, represented by 8 bits of a byte GB2312: Chinese encoding table, using two bytes to denote Chinese encoding GBK: Chinese encoding table upgrade, fusion of more expressions Chinese characters replacement version of GB18030:GBK BIG-5: Peer and RTHK area, is a traditional Chinese coding scheme, commonly known as "Big Five yards" UICode: International standard Code, fused with a variety of text UTF-8: is a Unicode encoding implementation that uses up to three bytes to represent one character      GBK Code Chinese occupies 2 bytes, English occupies 1 bytes UTF-8 Code Chinese occupies 3 bytes, English occupies 1 bytes utf-16be Code Chinese occupies 2 bytes, English occupies 2 bytes Java is a double-byte encoding utf-16be, which takes two bytes per character in Java         when you want to turn a byte sequence into a string, what encoding is used for the byte sequence, and what encoding is used to display the call S.getbytes ("encoded format of the byte sequence"), otherwise garbled A text file is a sequence of bytes, which can be any encoded sequence of bytes, but if a text file is created directly on a Chinese machine, the text file only knows the ANSI (local encoding) encoding. For example, create a new TXT file, the content is Unicom, open will be garbled, is a coincidence, just in line with the UTF-8 code rules     integer.tohexstring (Byte);//Display in 16-binary mode
second, the use of the file tool class 1. The file class is used to indicate that files and directories can be The file class is used only for information (name, size, etc.) that represent files (directories) and cannot be used for access to file content 2. The basic API of the file class (see manual)                  the condition of the constructor Create features: CreateNewFile (), mkdir (), mkdirs () Delete function: Delete () Rename function: Renameto () Judging function: Isfile (), Isdirectory (), exists ( ), etc. Get Features: GetName (), GetPath (), list (), etc. the role of the file filter: List (filenamefilter filter), returns a listing of files that meet the specified criteria                  when judging the parameters, you can use the illegalargumentexception parameter throws an exception file.separator Set directory separators, both Windows and Unix recognize relative directory is the current directory, that is, in the root directory of the project 3. Traverse directory (Recursive Dir.listfiles ()) The file system is accessed because it interacts with resources other than the JVM, so write code must be rigorous, taking into account the various situations               third, the use of Randomaccessfile class 1. Randomaccessfile Java provides access to file content that can be read or written and support random access files, can access any location of the file 2. java File Model The file on the hard disk is stored in byte byte Byte and is a collection of data 3. Open File  
1 Randomaccessfile RAF =newrandomaccessfile (file, "RW"); // RW, read/write, R Read Only // when opening a file, the file pointer is at the beginning, pointer = 0; 3 Raf.write (byte); // The Write method writes only one byte while the direct pointer points to the next position int b = raf.read (); // each time a byte is read, each character in Java occupies two bytes, and a 8-bit right shift is used to write 5 raf.seek (pointer position) in a split-second way; // Move the pointer 6 raf.close (); // file read and write must be closed, otherwise there may be unintended consequences
This approach has great benefits when files are downloaded, and each thread downloads a portion of the file, and then splicing together, Thunderbolt is used in this way, will record the position of the pointer Four, Byte stream (InputStream, OutputStream, two are abstract classes) 1. I/O streams are used to process data transfer between devices InputStream Abstracts the way the application reads data              OutputStream Abstracts the way the application writes data 2, EOF = end read-1 reading to the end 3, the basic way of input stream is mainly read int b = In.read ();//read one byte unsigned fill to int eighth bit, 1 is EOF In.read (byte[] buf);//read into a byte array filled with multiple bytes 4, the basic mode of output stream is mainly written out.write (int b); out.write (byte[] buf); 5, FileInputStream Specific implementation of the file read operation While ((B=in.read ())!=-1) {read a file} in.close ();//must remember to close the flow release system resources Bulk Read (very fast, high efficiency) vs. single-byte reading (not suitable for reading large files, very inefficient) 6, FileOutputStream Specific implementation of the file to write data operation whether to delete the file re-create, or append the content to the original file, see the construction method copy operations for your own files Out.flush (); out.close (); 7. Data input/output stream Dataoutputstream/datainputstream the extension of convection function, is a wrapper class, can be more convenient to read Int,long, characters and other types of data, the essence is the use of a decorative pattern implemented 8, byte buffer stream Bufferedinputstream/bufferedoutputstream provides buffer-only operation for I/O, which improves I/O performance . write (); . Flush ();//flush buffer otherwise not written to file . Close (); v. Character stream (Reference API) 1. Why does Java introduce a character stream? It is inconvenient to manipulate text, especially characters that contain non-ASCII code such as Chinese characters. character stream = byte stream + encoding So, be very clear about the coding problem.     2. The Java text (char) is a 16-bit unsigned integer, which is the Unicode encoding of the character (double-byte) file is a byte of byte byte ... The data series A text file is a stored sequence of text that is serialized as a byte in a coded way 3, Character stream (Reader Writer) operation is a text file processing one character at a time, the bottom of the character is still the basic byte sequence InputStreamReader Complete byte stream parsing to char stream by encoding OutputStreamWriter provides a char stream parsed into a byte stream by encoding 4, file read and write stream FileReader, FileWriter Unable to set encoding, must return to character stream set encoding 5, character stream filter BufferedReader, BufferedWriter, PrintWriter ReadLine can read one line at a time and write one line at a time you can set the encoding, do not recognize line breaks, write out the line-wrapping operation separately Vi. serialization and deserialization of objects 1. Convert object object to byte sequence, and reverse the deserialization of objects 2, serialized Stream (ObjectOutputStream), is the filter stream---writeobject () deserialization Stream (ObjectInputStream),----readobject 3. Serialized Interface (Serializable) object must implement a serialization interface for serialization, or an exception will occur This interface does not have any method, just a standard, is the tag interface              after the object is serialized, if you modify the class file again, then the deserialization will be a problem, then how to solve it? you need to set the serial version ID and the unique tag in the class so that no matter how you modify the ReadSerialversionuid

4. Transient key words the declared element does not serialize the JVM by default, or it can do its own serialization of the element not all elements are necessary for transmission in the network, especially when it comes to saving network traffic in some cases, it can help us improve performance (ArrayList only serializes valid elements when the array is not full) 5. Serialization of a neutron class and the invocation of a parent class constructor The parent class implements the serialization interface, and the subclass does not need to be implemented again to serialize when a sub-class object is deserialized, the constructor of its parent class is called if its parent class does not display an implementation-serialized interface . Vii. Some wrapper classes for input and output streams 1. Print Flow PrintStream: Byte print stream PrintWriter: Character Print stream integrated print () format output method to manipulate any type of data 2. Standard input/output stream in, out fields of the system class The default input device is the keyboard, the output device is the monitor                 Standard IO redirection System.setin (inputstream); //redirect output can write log to file to the console system.setout (printstream); System.err (printstream); 3. Process Control executes other operating system programs inside Java and requires control over the input and output of these programs pass a command string to Osexecute.command ()   
New Processbuilder (Command.split ("")). Start (); Osexecute.command ("JAVAP test"); // JAVAP is an anti-compiler program for Java

Viii. exception handling during IO operation

         oneself programming to surround with try-catch-finally, if have unusual to deal with, do not just use Printstacktrace () to print the stack information, in finally in the flow of closed (judge the reference is not empty), To ensure that it will be implemented.

Java-io input and output stream

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.