Understand the way Java handles text files and byte files

zhaozj2021-02-12  153

The data saved in the computer is only binary symbols and saved by bytes. It seems that the character A is not a character A, but is just a meaningless binary number is a byte. Most methods we provide when using Java IO classes for reading and write data, all methods of reading and writing bytes, and by this way of reading and writing bytes is to save any type of data, Because the data type is a zodical code in the computer, the premise is that you must first convert the data you write first into byte type and then output through the output stream, but to make the data read for our procedure. Significance, we must convert the read bytes to the meaning expressed by it, such as: Save is a char type, then we will convert the read-up data type to a char type restore It comes to express the meaning of it, or if it is only a 16-based symbol, it is meaningless if it is directly output. So, in the Java byte type is a universal data type, but also the true appearance of the data in the computer.

Java's IO classes In order to facilitate our input to outputs those basic data types, it is basically a read and write method for specialized various basic data types in various IO classes. These methods are actually packaged. , Such as: Readint WriteInt, but it seems to have a method of reading and writing String types because Java provides IO classes that read and write text characters, such as: Reader Writer, two abstract base classes, and derived by it The subclasses come out are specially used to read and write text characters. Therefore, if you want to read the text file, you don't go with the IO class of the InputStrem Outstrem, and use Reader Writer's class, because they are not for text, if you want to use it You have to set a dedicated program code in the program to do these characters. The following code shows:

Randomaccessfile ra = new randomaccessfile ("c: //1.txt", "rw"); // randomaccessfile class does not support direct reading and writing of characters

String s = new string ("Hello World");

Ra.write (s.getbytes ()); // converts String into byte types

Byte buf [] = new byte [1024]; // Defines a byte array to receive byte data read.

Raf.read (BUF, 0, 512); // RandomaccessFile class does not support direct reading of characters system.out.println ("name:" new string (buf)); // convert the byte data read into String and output.

转载请注明原文地址:https://www.9cbs.com/read-7507.html

New Post(0)