Java Fundamentals (ix)

Source: Internet
Author: User
Tags list of attributes readline thread class uppercase character

first, the computer stores the Chinese way in Eclipse
(1) Platform default encoding set: GBK, one Chinese corresponds to two bytes.
(2) The first byte: must be a negative number; the second byte: usually a negative number, which may also be a positive number, without affecting the result.
(3) For example:

public class Demo {    public static void main(String[] args) {        //定义一个字符串        String str = "大脑袋" ;        //转成字节数组        byte[] bys = str.getBytes() ;        System.out.println(Arrays.toString(bys));    }}

Results:

Second, decoding/encoding
1, encoding and decoding must be consistent before and after the encoding format.

2. Coding
(1) conversion process: string → byte → binary data
(2) Coding method:
A, public byte[] GetBytes (): Platform default encoding set encoding (default is GBK).
B, public byte[] GetBytes (Charset Charset); Specify format encoding.

3. Decoding
(1) Conversion process: binary data → decimal data → byte → string
(2) Decoding method:
A, public String (byte[] bytes) uses the platform default encoding set decoding (GBK).
B, public String (byte[] bytes,charset Charset): Decodes with the specified encoding format.

Three, byte buffer stream (high-efficiency byte stream)
1, byte buffer input stream Bufferedinputstream
(1) Construction method
A, public Bufferedinputstream (InputStream in): The default buffer size constructs a buffered input stream object.
B, public bufferedinputstream (inputstream in,int size): Specifies the buffer size to construct the buffered input stream object.
(2) Read mode
A, public int read () reads one byte at a time.
B, public int read (byte[] b,int off,int Len) reads part of a byte array at a time.
(3) For example, reading one byte array at a time:

public class BufferedInputStreamDemo {    public static void main(String[] args) throws FileNotFoundException,IOException{        //创建字符缓冲输入流对象        BufferedInputStream bis=new BufferedInputStream(                new FileInputStream("a.txt"));        //一次读取一个字节数组        byte[] bys=new byte[1024];        int len=0;        while((len=bis.read(bys))!=-1) {            //创建一个String对象,将读取到的字节数组转换为String类型输出            System.out.println(new String(bys,0,len));        }        //关闭流,释放资源        bis.close();    }}

2. Character buffered output stream
(1) Construction mode
A, public bufferedoutputstream (OutputStream out) constructs a byte buffered output stream object with the default buffer size.
B, public bufferedoutputstream (outputstream out,int size) Specifies the size of the buffer to construct the buffered output stream object.
(2) How to write data
A, public int write (int by) writes one byte at a time.
B, public int read (byte[] b,int off,int len) is part of an uppercase and lowercase array.
(3) Refresh function: void Flush () flushes the stream of the buffer.
(4) For example, one section of an array of write-in:

public class BufferedOutputStreamDemo {    public static void main(String[] args) throws FileNotFoundException,IOException{        //创建字符缓冲输出流对象        BufferedOutputStream bos=new BufferedOutputStream(                new FileOutputStream("a.txt"));        //一次写字节数组的一部分        bos.write("大脑袋".getBytes());        //关闭流,释放资源        bos.close();    }}

3. Character buffer stream copy files (take one byte array at a time as an example)

public class BufferedCopy {    public static void main(String[] args) throws Exception{        //封装        BufferedInputStream bis=new BufferedInputStream(new FileInputStream("a.txt"));        BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("b.txt"));        //一次复制一个字节数组        byte[] bys=new byte[1024];        int len=0;        while((len=bis.read(bys))!=-1) {//读取数据            //写数据            bos.write(bys,0,len);            //刷新            bos.flush();        }        //关闭资源        bos.close();        bis.close();    }}

5. (Interview questions) how to construct byte buffer stream Why can't I pass the path/file directly?
Solution: The buffered stream simply provides an array of buffers within the underlying, and the underlying implementation file's copy/read/write operations depend on the underlying stream object.

6. Common exception: illegalargumentexception Specifies the buffer size out of bounds exception.

Four, character stream (solve the problem of Chinese garbled)
1. Character Input stream reader
(1) An abstract class that uses its subclasses when creating an object.
(2) Sub-category:
A, character conversion input stream: InputStreamReader
B, Convenient class: FileReader
(3) character conversion input stream construction method
A, public InputStreamReader (InputStream in): The default encoding method constructs the character conversion input stream.
B, public inputstreamreader (InputStream In,charset CS) Specifies the encoding method to construct the character conversion input stream.
(4) Character input stream read Data mode
A, int read (char[] CHS) reads one character array at a time.
B, int read () reads a single character at a time.

3, character output stream writer
(1) An abstract class that uses its subclasses when creating an object.
(2) Sub-category:
A, character conversion output stream: OutputStreamWriter
B, Convenient class: FileWriter
(3) character conversion input stream construction method
A, public outputstreamwriter (OutputStream out): Constructs a character transformation output stream object using the default encoding format.
B, public OutputStreamWriter (OutputStream out, Charset CS): Constructs a character transformation output stream object using the specified encoding format.
(4) Character output stream write Data mode
A, public void write (int c) writes a single character at a time.
B, public void Write (char[] cbuf) An array of uppercase characters.
C, public abstract void write (char[] cbuf, int off, int len) is part of an uppercase character array.
D, public void Write (string str) writes a string at a time.
E, public void Write (string str,int off, int len) is part of a write string at a time.

4, (interview) The difference between the flush and close methods:
(1) Close closes the stream, closes the stream object, and the resource file associated with it, and after it is closed, it can no longer manipulate the convection object, or there will be an exception.
(2) Flush refreshes the stream, in order to prevent some files (picture files/audio files) missing or not loaded into the stream object. Whether the stream is refreshed or can be manipulated by a stream object.

5. copy files using character stream (one character array at a time)

public class Copy {    public static void main(String[] args) throws Exception{        //封装        FileReader fr=new FileReader("e:\\BR苏苏不酥\\大脑袋.txt");        FileWriter fw=new FileWriter("e:\\BR苏苏不酥\\Bighead.txt");        //一次复制一个字符数组        char[] chs=new char[1024];        int len=0;        while((len=fr.read(chs))!=0) {            fw.write(chs,0,len);            //刷新流            fw.flush();        }        //关闭资源        fw.close();        fr.close();    }}

Five, character buffer stream (more efficient)
1. Character buffered input stream BufferedReader
(1) Construction method
A, public BufferedReader (Reader in) creates a buffered character input stream using the default size input buffer.
B, public BufferedReader (Reader in, int sz) creates a buffered character input stream using the specified size input buffer.
(2) Unique function: public String readLine () reads one line at a time.

2, character buffered output stream Bufferedwrier
(1) The text is written to the character output stream, which buffers individual characters, providing efficient writes of individual characters, arrays, and strings.
(2) Construction method
A, public bufferedwriter (Writer out) default buffer size constructs A character buffer output stream object.
B, public bufferedwriter (Writer out,int size): Specifies the buffer size to construct the character buffer output stream object.
(3) Unique function: public void newLine () writes a delimited (newline) of a line.

3. Copy the file using the character buffer stream (for example, one line at a time)

public class CopyTeyou {    public static void main(String[] args) throws Exception{        //封装文件        BufferedReader br=new BufferedReader(new FileReader("e:\\BR苏苏不酥\\大脑袋.txt"));        BufferedWriter bw=new BufferedWriter(new FileWriter("e:\\BR苏苏不酥\\Bighead.txt"));        //一次复制一行        String line=null;        while((line=br.readLine())!=null) {            bw.write(line);            //写入一个行的分隔符号            bw.newLine();            //刷新流            bw.flush();             }        //关闭流,释放资源        br.close();        bw.close();    }}

4. Store the contents of the collection in a text file

public class ArrayListToTxt {    public static void main(String[] args) throws Exception{        //创建集合对象        ArrayList<String> al=new ArrayList<String>();        //添加元素        al.add("Bighead");        al.add("0829");        //创建字符缓冲输出流对象        BufferedWriter  bw=new BufferedWriter(new FileWriter("e:\\BR苏苏不酥\\Bighead.txt"));        //遍历集合        for(String s:al) {            //将遍历到的元素写入文本文件中            bw.write(s);            bw.newLine();            //刷新            bw.flush();        }        //释放资源        bw.close();    }}

5. Add content from a text file to the collection

public class TxtToArrayList {    public static void main(String[] args) throws Exception{        //创建字符缓冲输入流对象        BufferedReader  br=new BufferedReader (new FileReader ("e:\\BR苏苏不酥\\Bighead.txt"));        //创建集合对象        ArrayList<String> al=new ArrayList<String>();        //读取文本文件中的内容,一次读取一行        String line=null;        while((line=br.readLine())!=null) {            //将读取到的内容添加集合中            al.add(line);        }        //遍历集合,输出元素        for(String s:al) {            System.out.println(s);        }    }}

VI. Memory Operation Flow
1, overview: Applies to temporary storage files. After a program ends, the variables of these programs disappear from memory the memory operation flow is the read write to the data that disappears immediately.
2. Memory operation input Stream Bytearrayinputstream
Construction method: Bytearrayinputstream (byte[] buf)
3. Memory operation output Stream Bytearrayoutputstream
Construction method: Bytearrayoutputstream ()

Vii. Data Flow
1. Overview: Read and write for Java basic types of data.
2. Data input stream DataInputStream
3. Data output stream DataOutputStream

Eight, print flow
1, overview: PrintWriter, print flow, belongs to the output stream.
2. Features:
(1) can only write data (only for the destination file operation), cannot read the data (not for the source file operation).
(2) can be operated directly against the file. If a constructor in a class has a file object or a string type of data, the class can manipulate the text file directly.
(3) Automatic refresh function: PrintWriter (outputstream out/writer out,boolean AutoFlush), the second parameter if True, indicates that the automatic refresh function is started.
(4) Printing method print (xxx x)/println (xxx xx)
3. Classification:
(1) Character print stream (operation printwriter for text)
(2) byte print stream (PrintStream and standard output stream have relationship System.out;)

Ix. Merging flows
1, Overview: Sequenceinputstream represents the logical concatenation of other input streams (merging streams).
2. Construction Method:
(1) Public sequenceinputstream (InputStream s1, InputStream S2)
(2) Public Sequenceinputstream (enumeration e)

X. Standard input/output stream
1. Standard input stream: InputStream in = system.in;
2. Standard output stream: PrintStream out = syste.out; use BufferedWriter to wrap System.out. function: public void println (String x)

3. Keyboard input
(1) Scanner (JDK5 for later use)
(2) BufferedReader package character conversion input stream, package system.in (Stream mode keyboard entry, Java decorator mode)

Xi. Serializable
1, overview: Serializable tag interface, no construction method, no fields, there is no method.
2. Common anomalies
(1) Java.io.InvalidClassException: The sequence version number of the class does not match the version number of the class descriptor read from the stream.
(2) Java.io.NotSerializableException: The current class does not implement a serialization feature exception.
3, solve the problem that need multiple serialization: let the current implementation of the class serialization function of this class to produce a fixed ID, click on the program's XXX warning line, you can generate a fixed ID.
4. Some properties do not want to be serialized workaround: Transient Property Type property
5. When manually modifying the attribute/member variable of a tag class, the serialized version ID is changed.

12. Serialized stream/deserialization stream
1, serialized stream ObjectOutputStream.
(1) Serialization: The object is stored as a stream in a text file or transmitted in a network, object → stream data.
(2) Construction method: Public ObjectOutputStream (OutputStream out)
(3) Write function: Public final void WriteObject (Object obj)
2, deserialization stream objectinputstream.
(1) Deserialization: A Stream object in a text file or a stream object in a network transmission is restored to an object, stream data → object.
(2) Construction method: Public ObjectInputStream (InputStream in)
(2) Read function: Public final Object ReadObject ()
3. Using the serialization/deserialization function, the custom class needs to implement the serializable interface and override the ToString () method. The custom class implements the markup interface, which means the tag class.

13. Properties
1, Overview: Properties, represents a persistent set of properties (Abbreviation: Property collection Class) extends Hashtable<k,v> map collection. Can be saved in a stream or loaded from a stream, and each key and its corresponding value in the attribute list is a string.
2. Non-parametric construction: public Properties ()
3, Unique features:
(1) Public Object setProperty (string key, String value): Adds a key and value to the list of attributes, and forces both to use String.
(2) Public set<string> stringpropertynames (): Traverse
(3) public string GetProperty (string key) searches for properties in this property list with the specified key.
4, can be saved in the stream or loaded from the stream, only use the Property collection class:
(1) public void Store (Writer writer,string Comments): Saves the data in the collection in a text file (attribute collection).
(2) public void load (Reader reader): Loads data from a text file into a collection of properties.

14. Multithreading
1. Basic Concepts
(1) Single thread: The execution path of the program is only one.
(2) Multithreading: The execution path of the program has a number of lines. The execution of threads in the preemption of CPU (preemption resources), the execution of multithreading is random.
(3) Process: Independent allocation of the system and an inseparable unit. Threads depend on the existence of a process.
(4) Thread: A separate unit of the process. There are multiple tasks in a process that treat each task as a thread.
(5) Synchronized: Sync (Sync Lock).
2. Thread class (available in Java)
(1) Steps to implement multi-threaded procedures:
Way One:
A, the class is declared as a subclass of Thread;
B, the subclass should rewrite the Thread class of the Run method;
C. Create the object of this custom thread class on the main thread.
Way two:
A, customize a class, implement Runnable interface;
B, the implementation of the interface of the Run method, the time-consuming code to operate;
C, then creates the object in the main thread, makes the class object A resource class, creates an object of the Threadd class, and passes the resource class just as a parameter.
(2) Common methods:
A, public final void SetName (String name): Name the thread.
B, public final String getName (): Gets the thread name.
C, public static Thread CurrentThread (): Returns a reference to the currently executing thread object.
(3) Thread priority-related methods:
A, public final int getpriority (): Returns the priority of the thread.
B, public final void setpriority (int newpriority): Change the priority of the thread.
C, thread default priority
A, public static final int max_priority 10 maximum priority
B, public static final int min_priority 1 min priority
C, public static final int norm_priority 5 default Priority
(4) Other methods:
A, public final void Setdaemon (Boolean on): when the parameter is true, it is represented as a daemon thread. Mark the thread as either a daemon thread or a user thread. When a running thread is a daemon thread, the Java virtual machine exits. (The daemon does not end immediately, it will execute for a period of time at the end),
The method must be called before the thread is started.
B, public final void Join (): Waits for the thread to terminate. Interruputedexception Interrupt exception.
The C, public static void sleep (long Millis) thread sleeps, specifying the time millisecond value.
D, public final void Stop (): Forces the thread to stop executing and no longer executes. (The method is obsolete, but can still be used).
E, public static void yield (): Pauses the currently executing thread object and executes other threads.
3. Related questions
(1) is the JVM multithreaded? How many threads are there at least?
Solution: Jvm,java virtual Machine, identify main (main thread). The JVM is multithreaded, with at least 2 threads.
(2) How to implement multi-threaded program?
Solution: A, method one: To implement multi-threaded programs, you need to open processes, open processes, the need to create system resources, but the Java language can not create system resources, only C + + to create system resources, using C language to create a good system resource implementation.
B, method Two: A, a custom class, to implement the Runnable interface; b. Implement the Run method in the interface, manipulate the time-consuming code; C, then create the object in the main thread, make the class object as a resource class, create an object of the Threadd class, Pass the resource class just as a parameter.
(3) difference between stop () and interrupt ():
Stop (): Force the thread to stop executing and the program will no longer execute (this method is obsolete but still available).
Interrupt (): Middle thread, indicating a state of the thread break.
(4) Wait () differs from sleep ():
Wait (): When the Wait () call is called, the lock is released immediately (synchronous lock/lock Lock).
Sleep (): The thread sleeps, and the lock is not released when called.

Java Fundamentals (ix)

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.