Java Note 20. File access classes for in-depth parsing of I/O programming

Source: Internet
Author: User

In- depth parsing of I/O programming file access classes reprint please indicate source:http://blog.csdn.net/u012637501( embedded _ small J Sky ) before we start learning the byte stream class, let's take a look at the class-file class related to the file. The file class is the only object in the IO package that represents the disk file itself , and the fileclass defines a platform-independent way to manipulate files , and by invoking the various methods provided by the file class, we are able to create, delete, Rename the file and determine the file's read and write permissions and whether it exists, set and query the file's last modified time, and so on. In Java, the directory is also used as file, just a few of the directory-specific features---can use the list method to list the name of the file in the target. first, the file class (1) functionThe file class is the only object in the IO package that represents the disk file itself, and the file class defines some platform-independent methods to manipulate the files. However, the file class cannot access the contents of the files, that is, it cannot read data from a file or write data to a file, it can only manipulate the properties of the file itself . (2) Construction method>file (String pathname): Creates a file object whose contents are the files corresponding to the string path; >file (Uri uri): Creates a file object whose contents are the files that the URI contains; Example: File F=new file ("C:\\Test.txt"), create a file class instance F, the content of the instance directly corresponds to the C-drive directory Test.txt file,all the methods of the file class are . (3) Common methodsboolean createnewfile (): When the file does not exist, create a new empty file (the file name is pathname (contains path));Boolean Delete (): Deletes the file or directory represented by the abstract path name;Boolean exists (): Determines whether the file or directory represented by the abstract path name exists;string GetAbsolutePath (): Returns the absolute path of the file as a string;string Getcanonicalpath (): returns the relative path of the file as a string; String getName (): Gets the file (directory) name of the file/directory;Long LastModified (): Returns the last modified time of the file;long Length (): Returns the length (size) of the file; string[] List (): Returns all file names (directories) in this directory as an array of strings ; Boolean setreadable (Boolean readable): Sets the readable permission of the file;Boolean setwritable (Boolean writable): Sets the writable permission of the file;boolean isdirectory (): Determines whether it is a directory;boolean isfile (): Determines whether it is a file;boolean canRead (): Determines whether the file or directory is readable;boolean canWrite (): Determines whether the file or directory is writable;Note: The above method operates on a disk file or directory represented by the path of the file object.
Second, Randomaccessfile class 1. Functionthe Randomaccessfile class is the most extensive file access class in the Java language and provides a large number of ways to access files . The Randomaccessfile class supports a " random access " approach that uses the class implementation to jump to and read data anywhere in a file. In addition, the Randomaccessfile object class has a positional indicator pointing to the current read and write location, and when the N bytes are read and written, the file indicator points to the next byte of the N-word section. It is important to note that the class is limited to manipulating files and cannot access other IO devices (such as networks, memory images). 2. Construction Methodrandomaccessfile (file file, String mode)randomaccessfile (string name, string mode)Example:new Randomaccessfile (F, "RW"); Instantiate a Randomaccessfile object in a read-write mannernew Randomaccessfile (F, "R"); Instantiate a Randomaccessfile object in read-only modeWhen you open a file in read-write mode (referencing the variable f corresponding file), the program is created automatically if the file does not exist . 3. Common Methodsvoid Close (): Closes the random Access file stream and frees the system resources associated with the file stream;long Getfilepointer (): Returns the position indicator pointing to the location where the file is currently read and written;long Length (): Returns the length of the file;int Read (): reads a byte of data from the file;int read (byte[] b): reads up to B.length () bytes of data from the file to the byte array (byte[]);int read (byte[] b, int off, int len): reads len bytes of data from the file's off position to a byte array (byte[]);byte ReadByte (): Reads a byte of data from the file;Char readxxx (): reads a character from the file/double type/float data;String ReadLine (): reads the next line of data from the file;void Seek (Long POS): Sets the position indicator offset position (relative to the beginning of the file);int skipbytes (int n): skips n bytes;void Write (byte[] b): writes B.length bytes of data from the specified byte array to the file;void Write (byte[] b, int off, int len): writes Len Byte data after the off position of the specified byte array to the filevoid Write (int b): Writes a byte of data into the file; 4. Source Code Combat 1. Create and read a text file using Randomaccessfile (1) Employee.javafunction: Design a class to encapsulate employee information, an employee's information is a record in the file, in order to accurately locate each record in the file location, we make each record in the file of the same size, that is, each employee's Name field in the file length is the same. Package test;
<span style= "FONT-SIZE:18PX;"  >/* Custom classes: Information for encapsulating employees */public class Employee {String name; int age; final static int len=8;//length of the name public Employee (string Name,int age)//construct method {  if (name.length () >=len)  {   name=name.substring (0, Len);//How to name a length greater than 8 characters to take only the first 8  }  else  {   while (Name.length () <len)       name=name+ "\u0000";  }  This.age=age;  This.name=name; }}</span>

Source Analysis: In order for the name to meet the 8-character condition, we can do this: less than 8 characters to fill the space (that is, + "\u0000"), more than 8 to remove the back of the redundant parts. In addition, because the age is integer data regardless of how large the number, as long as it does not exceed the range of integer data, in memory is accounted for 4 bytes size. The string.substring (int beginindex,int endIndex) method is used to remove part of a substring from a string, and it is important to note that the first character in the string corresponds to the character in the original string marked as Beginindex. , but the last character corresponds to the character in the original string, not the character at Endindex, but the script in the endIndex-1. (2) Randomaccessfiletest.java function: Implement using Randomaccessfil The Class E creates and operates a text file, writes data to the file, and then reads the data from the file to print at the specified location.
<span style= "FONT-SIZE:18PX;" >package Test;import Java.io.randomaccessfile;public class Randomaccessfiletest {public static void main (string[] args) throws Exception {Employee E1 = new Employee ("Zhangsan", 30);//instance and initialize 3 Employee objects Employee e2 = new Employee ("Li  Si ", 26);  Employee E3 = new Employee ("Wangwu", 25); /*1. Open file after writing data off/randomaccessfile RA = new Randomaccessfile ("C:\\employee.txt", "RW");// Instantiate and open a Randomaccessfile representative's file Ra.write (E1.name.getBytes ());  Writes the first employee information to the file represented by the Randomaccessfile Ra.writeint (e1.age);  Ra.write (E2.name.getBytes ());  Ra.writeint (E2.age);  Ra.write (E3.name.getBytes ());  Ra.writeint (E3.age);  Ra.close ();  /*2. Open file again after reading file off */randomaccessfile RAF = new Randomaccessfile ("C:\\employee.txt", "R");  int len=8;  Raf.skipbytes (len+4);//Skip first employee information, with name 8 bytes, age 4 Bytes//Get second employee information System.out.println ("Second employee information:");  String str= ""; for (int i=0;i<len;i++) str = str + (char) raf.readbyte (); Reads a byte of information into STR, where the position indicator points to the 9th byte position (if starting at 0) System.out.println ("Name:"+str);  System.out.println ("Age:" +raf.readint ());  Get the first employee information (position indicator position points to the beginning of the second employee information after reading the data) System.out.println ("First employee information:");  Raf.seek (0);  Str= "";  for (int i=0;i<len;i++) str = str + (char) raf.readbyte ();  System.out.println ("Name:" +str);  System.out.println ("Age:" +raf.readint ());  Get a third employee information System.out.println ("Third employee Information:");  Raf.skipbytes (LEN+4);  Str= "";  for (int i=0;i<len;i++) str = str + (char) raf.readbyte ();  System.out.println ("Name:" +str);  System.out.println ("Age:" +raf.readint ()); Raf.close (); Close the file, release the reference variable resource, and the system resources it occupies}}</span>

Effect Demo:

Java Note 20. File access classes for in-depth parsing of I/O programming

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.