Java File Operation summary, java file Summary

Source: Internet
Author: User

Java File Operation summary, java file Summary

Use of RandomAccessFile APIs

Pointer = 0; file pointer write method raf. write (int) --> write only the last eight digits of a single byte. At the same time, the Pointer Points to the next position. Prepare to write the read method int B = raf again. read () --> close after reading a byte read/write file.
Public static void testrandomaccessfile () throws IOException {File demo = new File ("demo"); if (! Demo. exists () demo. mkdir (); File file = new File (demo, "raf. dat"); if (! File. exists () file. createNewFile (); RandomAccessFile raf = new RandomAccessFile (file, "rw"); // pointer location System. out. println (raf. getFilePointer (); raf. write ('A'); // write only one byte System. out. println (raf. getFilePointer (); raf. write ('B'); int I = 0x7fffffff; // you can write only one byte at a time using the write method. If you want to write I, you have to write it four times. write (I >>> 24); // high 8-bit raf. write (I >>> 16); raf. write (I >>> 8); raf. write (I); System. out. println (raf. getFilePointer (); // you can write one directly. Int raf. writeInt (I); String s = "medium"; byte [] gbk = s. getBytes ("gbk"); raf. write (gbk); // write to the byte array System. out. println (raf. length (); // the pointer must be moved to the raf header to read the file. seek (0); // One-time read. Read the object content to the byte array. byte [] buf = new byte [(int) raf. length ()]; raf. read (buf); System. out. println (Arrays. toString (buf); for (byte B: buf) {System. out. println (Integer. toHexString (B & 0xff) + "");} raf. close ();}

WriteInt () method source code, write one


Image.png

IO stream (input stream, output stream)
Byte stream
1. byte stream
1) InputStream and OutputStream
InputStream abstracts how an application reads data.
OutputStream abstracts the way an application writes data.
2) EOF = End read-1 read to the End
3) basic input stream method
Int B = in. read (); read a byte unsigned to fill in the lower eight bits of the int. -1 is EOF
In. read (byte [] buf) read data to fill in the byte array buf
In. read (byte [] buf, int start, int size) read data is filled into the byte array buf, starting from the start position of the buf, storing the size data
4) basic method of output stream
Out. write (int B) writes a byte to the stream, and B's low 8 bits
Out. write (byte [] buf) writes the buf byte array to the stream
Out. write (byte [] buf, int start, int size)
5) FileInputStream ---> implements Data Reading on the file.
6) FileOutputStream implements writing byte data to the file.
7) DataOutputStream/DataInputStream
The extension of the stream function makes it easier to read data of Int, long, and character types.
DataOutputStream
WriteInt ()/writeDouble ()/writeUTF ()
DataOutputStream dos = new DataOutputStream (new FileOutputStream (file ));
8) BufferedInputStream & BufferedOutputStream
These two stream classes provide buffer-based operations for IO. Generally, the buffer is added when the file is opened for write or read operations. This stream mode improves IO performance.

Putting input into a file from an application is equivalent to pouring water in one tank into another:
FileOutputStream ---> write method party Yu and a drop to transfer the water
The DataOutputStream ---> writexxx () method is more convenient, which is equivalent to one worker and one worker transfer.
BufferedOutputStream ---> the write method is more convenient. It is equivalent to putting a pair of water in a bucket and then importing it into another bucket.

Use the in. read () method

/* Read the content of the specified file, output it to the console in hexadecimal format, and line feed every 10 bytes */public static void printHex (String filename) throws IOException {// read FileInputStream in = new FileInputStream (filename); int B; int I = 1; while (B = in. read ())! =-1) {if (B <= 0xf) {// Add 0 System before the number of units. out. print ("0");} System. out. print (Integer. toHexString (B) + ""); // convert integer B to a hexadecimal string if (I ++ % 10 = 0) System. out. println ();} in. close ();}

Use in. read (byte [] buf, int start, int size)
Reads data to the byte array, returns the data size, and cyclically outputs the byte array.

Public static void printhexbytearray (String filename) throws IOException {FileInputStream in = new FileInputStream (filename); byte [] buf = new byte [20*1024]; // read bytes in batches from in and put them into the buf byte array. The values are put from the first position, and the maximum number of bytes is put in buf. length returns the number of bytes read/* int bytes = in. read (buf, 0, buf. length); // One-time reading, indicating that the byte array is large enough int j = 1; for (int I = 0; I <bytes; I ++) {if (buf [I] & 0xff)> 0 & (buf [I] & 0xff) <= 0xf) {System. out. print ("0");} System. out. print (In Teger. toHexString (buf [I]) + ""); if (j ++ % 10 = 0) System. out. println ();} * // use the buf array cyclically to prevent the use of int bytes = 0; int j = 1; while (bytes = in. read (buf, 0, buf. length ))! =-1) {for (int I = 0; I <bytes; I ++) {// to avoid data type conversion errors, clear the 24-bit high System. out. print (Integer. toHexString (buf [I] & 0xff) + ""); if (j ++ % 10 = 0) System. out. println ();}}}

File Replication
// Directly create an object if the object does not exist. If yes, delete the object and create it. If append = true, append if it does not exist
FileOutputStream out = new FileOutputStream ("demo/out. dat ");

Public static void copyFile (File srcFile, File destFile) throws IOException {if (! SrcFile. exists () throw new IllegalArgumentException ("file" + srcFile + "nonexistent"); if (! SrcFile. isFile () throw new IllegalArgumentException (srcFile + "not a file"); FileInputStream in = new FileInputStream (srcFile); FileOutputStream out = new FileOutputStream (destFile ); byte [] buf = new byte [8*1024]; int B; while (B = in. read (buf, 0, buf. length ))! =-1) {out. write (buf, 0, B); out. flush (); // it is best to add} in. close (); out. close ();}
// Use the public static void copytFileByBuffer (File srcFile, File destFile) throws IOException {if (! SrcFile. exists () throw new IllegalArgumentException ("file" + srcFile + "nonexistent"); if (! SrcFile. isFile () throw new IllegalArgumentException (srcFile + "not a file"); BufferedInputStream bis = new BufferedInputStream (new FileInputStream (srcFile )); bufferedOutputStream bos = new BufferedOutputStream (new FileOutputStream (destFile); int c; while (c = bis. read ())! =-1) {bos. write (c); bos. flush (); // refresh the buffer} bis. close (); bos. close ();}

2. Streams
1) Encoding Problems
2) recognize text and text files
Java text (char) is a 16-bit unsigned integer and unicode (dubyte encoding)
The file is a data sequence of byte...
A text file is a storage result of serialized text (char) sequences into byte according to a certain encoding scheme (UTF-8, utf-16be, gbk)
3) reader writer ---> operates on text files
Processing a character at a time
The underlying character is still the basic byte sequence
Basic implementation of a stream
InputStreamReader parses byte streams into char streams and parses them according to Encoding
OutputStreamWriter provides char stream to byte stream, which is encoded

// Pay attention to the encoding problem public class IsrAndOswDemo {public static void main (String [] args) throws IOException {FileInputStream in = new FileInputStream ("G: \ 11.txt "); inputStreamReader isr = new InputStreamReader (in, "UTF-8"); // The default project encoding FileOutputStream out = new FileOutputStream ("G: \ 12.txt "); outputStreamWriter osw = new OutputStreamWriter (out, "UTF-8"); // int c; // while (c = isr. read ())! =-1) {// System. out. print (char) c); //} char [] buffer = new char [8*1024]; int c; while (c = isr. read (buffer, 0, buffer. length ))! =-1) {String s = new String (buffer, 0, c); System. out. println (s); osw. write (buffer, 0, c); osw. flush ();} isr. close (); osw. close ();}}

FileReader/FileWriter

public class FrAndFwDemo {    public static void main(String[] args) throws IOException {        FileReader fr=new FileReader("g:\\11.txt");        FileWriter fw=new FileWriter("g:\\13.txt");        char[] buffer=new char[2056];        int c;        while((c=fr.read(buffer,0,buffer.length))!=-1){            fw.write(buffer,0,c);            fw.flush();        }        fr.close();        fw.close();    }}

Filters of the upstream stream
BufferedReader ---> readLine reads a row at a time
BufferedWriter/PrintWriter ---> write a row

Public class BrAndBwOrPwDemo {public static void main (String [] args) throws IOException {BufferedReader br = new BufferedReader (new InputStreamReader (new FileInputStream ("g: \ 11.txt "))); // BufferedWriter bw = new BufferedWriter (new OutputStreamWriter (new FileOutputStream ("g: \ 123.txt"); PrintWriter pw = new PrintWriter (" g: \ 1234.txt "); string line; while (line = br. readLine ())! = Null) {System. out. println (line); pw. println (line); pw. flush (); // bw. write (line); //// write the line feed operation separately // bw. newLine (); // newLine operation // bw. flush ();} pw. close (); br. close (); // bw. close ();}}

Join the study exchange group 569772982 to learn and exchange.

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.