Java I/O hexadecimal explanation and I/O stream summary

Source: Internet
Author: User
Tags socket

In the Java World, 99% of the work is at this level. So where will binary and bytecode be used?

Self-help: In cross-platform scenarios, you will be highlighted. For example, file read/write, data communication, and Java compiled bytecode files. The following is an example of data communication.

Java implements the Serializablle interface on the object to convert it into a series of bytes. In communication, there is no need to express the relational data on different machines and the byte order. Here, the bricklayer will not explain the Serializablle interface in detail and will explain it separately later.


Java hexadecimal conversion

First, let's take a look at the data types in Java:

1. Int integer: byte (8 bits,-128 ~ 127), short (16 bits), int (32 bits), long (64 bits)

2. Float: float (32-bit) and double (64-bit)

2. char character: unicode character (16 characters)

That is to say, an int is equivalent to a 4-byte array.

In Java, how is the hexadecimal conversion?

In Java, Int shaping and char character wrapped classes provide a series of operation methods. For example, in java. lang. Integer, the api is shown in the following figure:

The following is a demo by the bricklayer.

Package javaBasic. oi. Byte.pdf;

Public class IntegerOper
{
Public static void main (String [] args)
    {
System. out. println ("17 hexadecimal:" + Integer. toHexString (17 ));
System. out. println ("17's octal:" + Integer. toOctalString (17 ));
System. out. println ("17 binary:" + Integer. toBinaryString (17 ));

System. out. println (Integer. valueOf ("11", 16 ));
System. out. println (Integer. valueOf ("21", 8 ));
System. out. println (Integer. valueOf ("00010001", 2 ));
    }
}

Right-click Run and we can see the following output in the console:

Hexadecimal: 11
Octal of: 21
Binary: 10001


Supplement: if the value is too large, you need to call the method provided by java. lang. Long.


Magic conversion of Java basic types and bytes

Here, the bricklayer thinks that he is a student, a typical OO thought. The student ID: 1206010035 is an integer. How can it be converted into Bytes? The object with bytecode mentioned above can communicate with each other. Therefore, the student ID of the school communicates in this way. Therefore, you must convert the student ID to a bytecode.

The bricklayer wrote a tool class IntegerConvert. java:

Package javaBasic. oi. Byte.pdf;

Public class IntegerConvert
{
/**
* Int to byte array
*/
Public static byte [] int2Bytes (int inta)
    {
// 32-bit Int can be stored in a 4-byte array
Byte [] bytes = new byte [4];
For (int I = 0; I <bytes. length; I ++)
Bytes [I] = (byte) (int) (inta> I * 8) & 0xff); // shift and clear
        
Return bytes;
    }
    
/**
* Convert byte array to Int
*/
Public static int bytes2Int (byte [] bytes)
    {
Int inta = 0;
For (int I = 0; I <bytes. length; I ++)
Inta + = (int) (bytes [I] & 0xff) <I * 8); // shift and clear
        
Return inta;
    }
    
Public static void main (String [] args)
    {
// Convert My student ID to bytecode
Byte [] bytes = IntegerConvert. int2Bytes (1206010035 );
System. out. println (bytes [0] + "" + bytes [1] + "" + bytes [2] + "" + bytes [3]);
// The bytecode can be converted back to the student ID
System. out. println (IntegerConvert. bytes2Int (bytes ));
    }

}

Run and right-click Run to view the following output:

-77 64-30 71
010035

The code is explained as follows:

1. (inta> I * 8) & 0xff

Shifts are cleared from left to right, and 1 byte is obtained in 8 bits.

2. Here we use the small-end method. The status byte is placed at the low address of the memory, that is, the starting address of the value. Supplement: 32-bit large-end mode (PPC) and short-end mode (x86 ).

Naturally, Long also has the following conversion methods:

Public class LongConvert
{
/**
* Long to byte array
*/
Public static byte [] long2Bytes (long longa)
    {
Byte [] bytes = new byte [8];
For (int I = 0; I <bytes. length; I ++)
Bytes [I] = (byte) (long) (longa)> I * 8) & 0xff); // shift and clear
        
Return bytes;
    }
    
/**
* Convert byte array to long
*/
Public static long bytes2Long (byte [] bytes)
    {
Long longa = 0;
For (int I = 0; I <bytes. length; I ++)
Longa + = (long) (bytes [I] & 0xff) <I * 8); // shift and clear
        
Return longa;
    }
    
}

What about the string and character array? For example, the name of the bricklayer: Li Qiangqiang

Java also provides a series of methods. In fact, java. lang. String encapsulates char []. In essence, it still operates on char arrays. The code is as follows:

Package javaBasic. oi. Byte.pdf;

Public class StringConvert
{
Public static void main (String [] args)
    {
String str = "Li Qiangqiang ";
Byte [] bytes = str. getBytes ();
// Print the byte array
System. out. println ("The byte array of 'Li Qiangqiang 'is :");
For (int I = 0; I <bytes. length; I ++)
System. out. print ("\ t" + bytes [I]);
    }
}

Right-click Run and you will see the following output:

The byte array of 'Li Qiangqiang 'is:
-64-18-57-65-57-65

Argument: Here we demonstrate a Chinese character, which requires two bytes, that is, a Chinese character is 16 bits.


Talking about data in Java communication

Below is a simple continuation of the story of the bricklayer student.


As shown in the figure, a student object in the database table has a student ID attribute. At this time, the client will send this object to the server. The process is as follows:

1. The object implements the Serializable interface.

Objects that implement the Serializable interface can be converted into a series of bytes and can be completely restored in the future.

2. The student id attribute value is 1206010035, which is converted from the client to the bytecode.

3. Transmit the bytecode to the server

4. The server receives and converts it to the object property value.



Java I/O stream summary

There are about 75 classes and interfaces in the java. io package. Java. io packages are designed to process data and object I/O operations. The programmer needs to use the java. io package to write data to a disk file, set the child, URL, and the system console, and read the input data from it. The java. io package also supports string data formatting, as well as zip and jar text processing.

I/O operations in java use a large amount of packaging processing. Therefore, two or three classes must be executed to implement simple I/O processing.

Wrapper is an object that can access its own features through other objects. The encapsulated object will enhance or improve the availability of the encapsulated object. This technology is widely used in Java I/O libraries. Packaging is a design pattern, which has also become a decorator design pattern. The java stream packaging mainly improves the efficiency of reading or outputting data.

Java has two types of streams: byte streams and byte streams. Each type of stream is divided into an input stream and an output stream. So how do I choose whether to use byte stream or byte stream during I/O operations?

Take the output as an example to solve the problem in three aspects:

1. Determine whether the output content contains any characters. If it contains characters, is it a 16-bit encoded character or an 8-bit encoded character?

If you print a report in the United States or Europe, you may need to use 8-bit encoding characters for output. If a database uses 16-bit Unicode characters, use a 16-bit encoded character output. Note that data should not be damaged when making the selection.

1) when an 8-bit encoded character is used for output, OutputStream is applied (default)

2) when a 16-bit encoded character output is used, the Writer class is applied.

2. Determine the purpose of data output

JAVA programs access external data through data streams. A dedicated underlying class is available for most physical output purposes.
Determine the OutputStream class that outputs 8 characters or the Writer class that outputs 16 characters based on the output purpose and data width.
File java. io. FileOutputStream java. io. FileWriter
Sets the child java.net. Socket. getOutputStream () sets the child to never use a 16-bit data stream.
URL (GET/POST) java.net. URLConnection. getOutputStream () URL is based on the socket child, so no
Pipeline java. io. PipedOutputStream java. io. PipedWriter
Array in memory java. io. ByteArrayOutputStream java. io. CharArrayWriter

3. Are you sure you want to determine the output data type, binary data? Or printable data?

Determine the class used by the top-level class type format hexadecimal value based on binary data, ASCII characters, and string output
4-byte binary integer java. io. DataOutputStream
Consecutive ASCII characters

Java. io. PrintOutputStream

Java. io. PrintWriter

We turn the class selected in this step into the top class.


For example

Suppose there is an array containing 1000 integers. We want to write them into a file in the form of binary data. The code is as follows:


FileOutputStream fos = new FileOutputStream ("ints. dat ");

DataOutputStrea dos = new DataOutputStream (fos );

For (int I = 0; I <1000; I ++ ){

Dow. writeInt (myArray [I])

}

Dos. close ();

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.