Learning 7--io file operations in CoreJava

Source: Internet
Author: User
Tags time 0

Includes the following classes and interfaces:

File class

FileFilter Interface

RandomAccessFile class


I. File class


Java. io. File is used to indicate the File directory). That is to say, the programmer can use the File class to operate the files and directories on the hard disk in the program.


The File class is only used to indicate the information Name and size of a File or directory. The File content cannot be accessed.


Constructor summary:


File (File parent, String child)

Creates a new File instance based on the abstract path name and child path name string of the parent.

File (String pathname)

Create a new File instance by converting a given path name string to an abstract path name.

File (String parent, String child)

Create a new File instance based on the parent path name string and the child path name string.

File (URI uri)

Create a new file instance by converting the given File: URI into an abstract path name.

/*** "." Indicates the current directory. the root directory of the project to which the current class belongs ** File. separator is a constant used to describe directory-level delimiters in different File systems. * Linux is/windows is \ **/File file File = newFile (". "+ File. separator + "file.txt"); // this parameter is not recommended ". /file.txt "cross-platform relationship/*** view file or directory-related content * // determine whether the file or directory exists in System. out. println (file. exists (); if (! File. exists () {// the file does not exist. Create a file. createNewFile ();}/** get file name */System. out. println ("file name:" + file. getName ();/** get file size */System. out. println ("file size:" + file. length ();/** file relative path */System. out. println ("file path:" + file. getPath (); // file path :. /file.txt/** absolute file path */System. out. println ("absolute file path:" + file. getAbsolutePath (); // absolute file path:/home/soft01/workSpace/JSD1305_JavaSE /. /file.txt/** the path described in the file system has a relative path. /This character */System. out. printl N ("path described in the file system:" + file. getCanonicalPath ();/** is it a file or a directory */System. out. println ("whether it is a file:" + file. isFile (); System. out. println ("whether it is a directory:" + file. isDirectory ();/** view the last modification date of the current file */longtime = file. lastModified (); Date date = newDate (time); SimpleDateFormat format = newSimpleDateFormat ("yy-MM-dd hh: mm: ss"); System. out. println ("Last file modification date:" + format. format (date);/** whether the file is readable and writable */System. out. println (file. canRead (); System. Out. println (file. canWrite (); System. out. println (file. canExecute ();/*** create/delete a file or directory * createNewFile () When and only when there is no file with the name specified by this abstract path name, A new empty file cannot be created separately. * Mkdir () creates the directory specified by this abstract path name. * Mkdirs () creates the directory specified by this abstract path name, including all required but non-existent parent directories. * Delete () deletes the file or directory represented by this abstract path name. * When the Virtual Machine ends, deleteOnExit () requests to delete the files or directories represented by this abstract path name. */File dir = newFile ("demo/demo1"); // do not use "." if (! Dir. exists () {dir. mkdirs ();} System. out. println (dir. getCanonicalPath (); // home/soft01/workSpace/JSD1305_JavaSE/demo/demo1if (dir. exists () {dir. delete (); // make sure the directory is empty}/*** view the directory content * String [] list () returns a String array, these strings specify the files and directories in the directory represented by this abstract path name. * String [] list (FilenameFilter filter) returns an array of strings that specify the files and directories that meet the specified filter in the directory indicated. * File [] listFiles () returns an array of abstract path names, which indicate the files in the directory represented by this abstract path name. * File [] listFiles (FileFilter filter) returns an array of abstract path names, which indicate the files and directories in the * directory that meet the specified filter. * File [] listFiles (FilenameFilter filter) returns an array of abstract path names. These path names indicate the files and directories that meet the specified filter in the * directory. * Static File [] listRoots () lists available File system root. * // ** List the directories or files under the current root directory */File f = newFile (". "); String [] dirs = f. list (); for (inti = 0; I <dirs. length; I ++) System. out. println (dirs [I]);


Ii. FileFilter Interface


Is an interface, which must implement an abstract method accept to define the rule for filtering files.


An instance of this interface can be passed to the listFilterFileFilter method of the File class.


File [] listFiles (FileFilter filter) returns an array of abstract path names, which indicate the files and directories in the directories that meet the specified filter.


FileFilter filter = newFileFilter () {@ Override publicbooleanaccept (File file) {// The file obtained by the filter is a File that ends with a txt file booleanbf = file. isFile () & file. getName (). lastIndexOf (". txt ")! =-1; returnbf ;}}; File file = newFile (". /"); File [] subs = file. listFiles (filter); for (File sub: subs) {System. out. println (sub. getName ());}


This mode is called [return mode] by calling a method and passing in an instance.


The listener used in swing is also a typical bounce mode.


Iii. RandomAccessFile class

Files are stored in byte by byte on the hard disk. Is a collection of data.

Open the file:

There are two modes: "rw (read/write)" and "r (read-only )"

RandomAccessFile raf = new RandomAccessFile ();

When opening a file, the default file pointer starts with pointer = 0.

Write method:

Raf. write (int) can write the "Low eight bits" of the integer to the file, and the pointer is automatically moved to the next position, ready to write again.

Read files:

Int B = raf. read () reads a byte (8 bits) from the file to fill in the eight bits of the int, the 24 bits are 0, and the return value range is 0 ~ 255. If-1 is returned, the object is read to the end of the object. After reading the object, the object pointer is automatically moved to prepare for the next read.


You must close the file after reading and writing the file.


When a RandomAccessFile does not exist, the file is automatically created.


File file = newFile ("file.txt"); if (! File. exists () {file. createNewFile ();}/** open the file as a read/write */RandomAccessFile raf = newRandomAccessFile (file, "rw "); /** write data to the file * call the write (int d) Method * write only one byte with a low 8 bits */raf. write ('A'); raf. write ('B'); intmax = 0x7fffff;/*** because the write (int B) method can only write one byte at a time *, write an int value to the file, it must be written four times in a row. ** The maximum binary value of the int type is 01111111 11111111 11111111 11111111 **. You need to store the high 8-bit data to the low 8-bit data, and use the shift operation, move 24-bit * int> 24*00000000 00000000 00000000 first * int> 16*01111111 00000000 00000000 01111111 second * int> 8*11111111 00000000 01111111 11111111 three times * The last time 0 bits are moved, it is equivalent to not moving */raf. write (max >>> 24); // 00 00 00 7fraf. write (max >>> 16); // 00 00 7f ffraf. write (max >>> 8); // 00 7f ff ffraf. write (max); // 7f ff/** JDK provides a write method based on the basic type. This is also achieved through shift. * Example: writeInt (int v) writeLong (long v) */raf. writeInt (max);/** write (byte [] data) */String info = "Hello Java! "; Raf. write (info. getBytes ("gbk"); System. out. println (raf. length (); // The number of bytes of the output raf. close ();

1. cache-based write Method


Write (byte [] B) writes bytes B. length from the specified byte array to this file, and starts from the current file pointer.

Write (byte [] B, int off, int len) Writes len bytes from the specified byte array to this file and starts from the offset off.


2. cache-based read Methods


Int read (): read one byte at a time, and the returned result is read to one byte. If it reaches the end of the file, the returned value is-1.


EOF: end of file


Int read (byte [] B) reads up to B. length data bytes from this file into the byte array.

Int read (byte [] B, int off, int len) reads a maximum of len data bytes from this file into the byte array.


File file = newFile ("file.txt");/** open the file as a read/write */RandomAccessFile raf = newRandomAccessFile (File, "rw"); inta = raf. read (); System. out. println (a); // read-1, which indicates to the end of the file. The file contains no content/** pointer position */System. out. println ("pointer position:" + raf. getFilePointer ();/*** cause: * RandomAccessFile performs read/write operations based on the cursor. * You must move the cursor to the start position of the file to start reading the file again. ** How to move the cursor: seek (int index) * moves to the specified position. 0 indicates the first byte at the beginning of the file. */Raf. seek (0); System. out. println ("pointer position:" + raf. getFilePointer (); a = raf. read (); System. out. println (char) a); raf. close ();


3. Random read/write Method


Seek (long pos) sets the file pointer offset measured at the beginning of the file, where the next read or write operation occurs.

Int skipBytes (int n) tries to skip the n Bytes of the input to discard the skipped bytes.


File file = newFile ("f.txt"); if (! File. exists () {file. createNewFile ();}/** open the file as a read/write */RandomAccessFile raf = newRandomAccessFile (file, "rw"); raf. write ("I Love Java and I Love Java. ". GetBytes ("GBK"); // read byte [] s = newbyte [31];/** int read (byte [] array) * will be up to array. length data bytes are read into the byte array from this file. * Returns the actual number of bytes read. */raf. seek (0); // raf. skipBytes (4); // skip n Bytes to discard the skipped bytes. Inta = raf. read (s); System. out. println ("the read bytes are:" + a); System. out. println (newString (s, "GBK"); // I Love Java and I Love Java. Raf. close ();

4. Read and Write strings


String readUTF () reads a String from this file.

Void writeUTF (String str) writes a String to the file in a machine-independent manner using UTF-8 encoding.

File file = newFile ("file.txt"); if (file. exists () {file. delete ();} file. createNewFile (); RandomAccessFile raf = newRandomAccessFile (file, "rw");/*** write the char value in two bytes */chara = '中'; raf. writeChar (a); // raf. writeChars ("Chinese"); // You can also directly use some strings. // This is not recommended here, because it is related to encoding, we should be the same encoding. /*** Because UTF-8 is the world's common encoding format * RandomAccessFile provides a way to read and write strings using this encoding format. * Void writeUTF (String str) * String readUTF () */raf. writeUTF ("Chinese, haha !!!! "); Raf. seek (2); // place the pointer to the starting position System. out. println (raf. readUTF (); // Chinese people, haha !!!! Raf. close ();


This article from the "beautiful life needs to carefully record" blog, please be sure to keep this http://huing.blog.51cto.com/1669631/1295084

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.