IO, documents, NIO "Two" __java the way of cattle

Source: Internet
Author: User
Tags file separator parent directory posix readable readline

http://blog.csdn.net/silentbalanceyh/article/details/5252280

(This chapter will talk about a more important chapter in Java, here to say sorry, because the reason for the recent change of work, there has been no time to continue writing tutorials, but then I will always adhere to the HA, I hope you can support.) This section mainly deals with commonly used file reads and writes, including advanced file IO content--java.nio, which is a fairly common part of some of today's projects, and if there are any omissions or clerical mistakes, I would like the reader to email us: Silentbalanceyh@126.com, thank you. This section may be much longer than the previous chapters, but also to ensure that the Java inside IO and file operations can be written to write all, if there are omissions hope that the reader to email, the concept of confusion in the place please tell, some of the contents of the reference to some of the original data translation and thinking notes. )
The contents of this chapter:
1.IO related content 2. Files and Directories 3. File Advanced Operations

2. Documents and Directories    I. Document Processing class:Java provides a dedicated file class for file processing:File, FileDescriptor, filepermission, RandomaccessfileAnd then cooperate with the top IO section of the class:FileInputStream, FileOutputStream, FileReader, FileWriterTo do the operation of the file, these classes constitute a common Java inside the structure of the file processing, if the omission of the reader to email instructions:silentbalanceyh@126.com, Java and C # are not the same one thing isFiles and directoriesThe abstract representation does notSeparation, in C # There are separate classes for files and directories to describe, while in Java there is a unified use of abstract file representations of files and directories.[1]file class Description:    the definition of the class is as follows:public class File extends Object implements Serializable,comparable<File>This class is an abstract representation of files and directories in Java, listing its commonly used list of methods for easy access by readers:Judgment Action:
Boolean canexecute ()
: Test whether an application can be executed, that is, whether a file can be executed against the platform, the application is an abstract pathname representation of the file, Linux platform because I have not used this class, it is estimated that. bin,. RPM or other format files, Windows is generally. exe,. BAT and. com files
boolean canRead (): Tests whether an application can read, that is, whether a file is readable
boolean canwrite (): Test whether an application or file is writable, in which case the file will return FALSE if it is not changed if it is set with a read-only property
boolean isabsolute (): Determines whether the abstract pathname of the file is an absolute or relative path
boolean isdirectory (): Test whether the file represented by this abstract path is a directory "the directory here can be understood as a common language: folder"
boolean isfile (): Tests whether the file represented by this abstract path is a standard file
boolean Ishidden (): Tests whether the file represented by this abstract path is a hidden file or a hidden directory
Boolean exists (): Tests whether the file or directory represented by this abstract path existsEnumeration Operation:
String[] List ():
Returns an array of strings that specify all the files and directories below the directory represented by this abstract path
string[] List (filenamefilter filter): As synonymous with the top method, a filter is added that satisfies the criteria for all filters defined by the
file[] Listfiles (): Returns an array of abstract paths whose result is an abstract path representation of all the file lists below the enumeration directory
file[] Listfiles (filefilter filter): Returns the abstract path array group that represents the files and directories in the directory represented by this abstract path name that satisfy the specified filter.
file[] Listfiles (filenamefilter filter): Returns an abstract path array group that represents the files and directories in the directory represented by this abstract path name that meet the specified filter, and the same as the top method
Static file[] Listroots (): Lists the available file system root directories
Here are two points:
> First:listroots ()Use this method to enumerate all the root directory, in fact, all exist in the system root directory generally is the letter, Linux may not be the same, when Windows calls the method, the final output list is an array of letter names, because the method isstatic Method, this approach is for all files, and for each operating system that has the Java platform installed, it is an enumerationRoot path of fileListing. Readers can try to write a simple program test test on their own platform.
> Second:About interfacesFilenameFilterAndFileFilter
FileFilter interface
Public Interface FileFilter (1.2):This interface is used for filters of abstract paths and contains only one method: Boolean accept (File pathname)--this method tests whether the abstract pathname is contained in a list of path names
FilenameFilter interface
Public Interface FilenameFilter (1.0):The class instance that implements the interface is available for the filter file name, and the interface contains only one method: Boolean accept (File dir,string name)--test whether the specified file is contained in a file listTo Modify an operation:
Boolean createnewfile ():
If and only if a new empty file is created directly when the filename is not present, return true successfully, and the failure returns false
static File createtempfile (String prefix,string suffix): Creates an empty file in the default temp directory, using the generated name of the given prefix and suffix
static File createtempfile (String prefix,string suffix,file directory): Creates a new empty file in the specified directory, using the generated filename of the given prefix and suffix
Boolean Delete (): Deletes the file or directory represented by this abstract path, deletes successfully returns TRUE, and fails returns false
void Deleteonexit (): When the virtual machine terminates, request to delete the directory or file represented by this abstract path name
boolean mkdir (): Creates the directory specified by this abstract path name
boolean mkdirs (): Creates the directory specified by this abstract path name, including all parent directories that must and do not exist
boolean Renameto (File dest): Renames the file name represented by the abstract pathsetting and fetching of properties:
Get PropertiesFunction:
File getabsolutefile ():Returns the absolute pathname of this abstract path name
String GetAbsolutePath ():Returns the absolute path string for the file or directory represented by this abstract path name
File getcanonicalfile ():Returns the canonical form of this abstract path name
String Getcanonicalpath ():Returns the canonical form string for this abstract path name
long Getfreespace ():Returns the number of unassigned bytes in the partition specified by this abstract path name
String getName ():Returns the name of the file or directory represented by this abstract path name
String getparent ():Returns the path name string for the parent of this abstract path name, or null if no parent directory is specified
File getparentfile ():Returns the path name of this abstract path parent path, or null if no parent directory is specified
String GetPath ():Converts this abstract path name to a path name string
long Gettotalspace ():Returns the partition size specified by this abstract path name
long Getusablespace ():Returns this abstract path specifies the number of bytes that the partition uses for this virtual machine
Long LastModified ():Returns the last time that the file represented by this abstract path name was modified
long Length ():Returns the length of the file represented by this abstract path
Setting PropertiesFunction:
Boolean setexecutable (Boolean executable):A convenient way to set this abstract path owner to execute permissions
Boolean setexecutable (Boolean Executable,boolean owneronly):Set execution permissions for this abstract path name owner or user
Boolean setlastmodified (Long time):Set the time of last modification
Boolean setreadable (Boolean readable):A convenient way to set read permissions for this file as the owner
Boolean setreadable (Boolean Readable,boolean owneronly):Sets the Read permissions for the owner or all users of this abstract path name.
boolean setreadonly ():Marks the file or directory specified by this abstract path name, so that it can be read only.
Boolean setwritable (Boolean writable):A convenient way to set this abstract path name owner Write permission.
Boolean setwritable (Boolean Writable,boolean owneronly):Sets the write permission for the owner or all users of this abstract path name."*: There are no listed ways to ask readers to view Java API documentation. "    [2]filedescriptor class:An instance of a file descriptor is used as an opaque handle to a structure associated with a base machine that represents an open file, an open socket, or another source or recipient of a byte, and the main practical purpose of a file descriptor is to create aFileInputStreamAndFileOutputStream, the application should not create its own file descriptor. When the class is constructed, it constructs an invalid object. The actual use of the words also need to be considered, here provides a fragment of the online excerpt "own translation": In fact, Sun in the design of this class is not want us to use it, see the official document can know that this class does not have the means to construct a legitimate instance object, That means there's no way to create a legitimateFileDescriptorThe instance of the class. The document has a display declaration: "applications should not create their own file descriptors”。 Here's a note for the file descriptor (FileName descriptor: Probably not very well translated here): In computer programming, a file descriptor is an abstract key to manipulating the file, which was previously used on a POSIX-structured operating system, on Windows , if you want to implement it using standard C's input output library, "file handle" files handle. At the top of the POSIX system, the file descriptor is actually a value of type int, and inside standard C is an int. Within each process, the file descriptor has three standard POSIX platform specifications:standard input (stdin): value is 0 standard Output (STDOUT): value is 1 Error Output (stderr): value is 2The structure of the diagram is as follows:
Generally speaking, a file descriptor is an index of the entire file structure within the System kernel entity during the opening of the file, which describes the details of the data structure inside the file. ——on a POSIX-structured operating system, this data structure is also called File Description chart, each run process also has its own built-in file descriptor, when the user runs an application, is to pass an abstract key that is the file descriptor to the system kernel to implement system calls, The kernel then returns a signal to the application by identifying and judging the system's application to tell it whether it can manipulate the file, which is based on the file descriptor, and the application itself cannot implement direct read-write operations against the file descriptor. ——within the UNIX architecture's operating system, the file descriptor can be referenced directlyfiles, directories, blocks, and character devices(also known as"Special Files")、ports, FIFOs(also known as a named pipe), and the file file handle is present in the standard library of C as a data structure that is used by the Routines Library reference to manage the file, which often includes low-level file descriptors to access the underlying objects of the UNIX operating system. ——inside the Windows operating system, as well as using file handles to refer to many of the underlying constructs, like the POSIX system file descriptor, Microsoft's C library also provides a compatible feature that runs the integer values supported by POSIX top support. "*: Well, don't pull away, otherwise you can't go on." 】[3]filepermission class:The class is defined as: Public final class Filepermission extends Permission implements Serializable This class represents access to files and directories that have an instance of the path name and a valid action on the pathname The path name is the pathname of the file or directory to which the specified action is granted. The pathname that ends with "/" (where "/" is a file separator character, or File.separatorchar) indicates all the files and directories contained in the directory. Path name ending with "/-"(recursively)Indicates all the files and subdirectories contained in the directory. By special marks"<<all files>>"The path name that is composed can match any file. Note: a single "*" Path name indicates all files in the current directory, whereas a single "-" pathname indicates all files in the current directory and (recursively) indicates all files and subdirectories contained in the current directory. The action to be granted is passed to the construction method as a string that contains a list of one or more comma-delimited keywords. The possible keywords are"read", "Write", "execute"And"Delete"。 The meaning is defined as follows: Read Read permission write Write permission execute execute permission. Allow call to Runtime.exec.  Corresponds to Securitymanager.checkexec. Delete Deletion permission. Allow call to File.delete.   Corresponds to Securitymanager.checkdelete. The action string is converted to lowercase letters before processing. Be careful when granting filepermission permissions. Be cautious when granting read access to various files and directories, and (in particular) write access. Grant for write operations"<<all files>>"Privileges are particularly dangerous. This allows write operations to the entire file system. In fact, it even allows binary files in the system(including JVM runtime environment)To replace it.[4]randomaccessfile class:The class is defined as: public class Randomaccessfile extends Object implements dataoutput,datainput,closeable instances of this class support therandom access to read and write files, random access to the file behaves like a large byte array stored in the file system, with a cursor or index pointing to the suppressed array, calledFile PointersThe input operation starts reading bytes from the file pointer, the file pointer is moved forward as the byte is read, and the output operation is available if the file is randomly accessed in read/write mode, and the output operation writes the byte from the file pointer and moves the pointer forward as the byte is written. The output operation after writing the current end of the suppressed array results in an extension of the array, which can be read by the Getfilepointer method and set by the Seek method. Typically, all of the read routines in this class have reached the end of the file before reading the desired number of bytes, throw eofexception, and throw a ioexception if there are reasons why no bytes can be read, instead of the end of the file before the desired number of bytes are read.   Instead of eofexception, in particular, it is possible to throw IOException if the stream is closed. The file location pointer for the object follows a few rules: The file location pointer for the new Randomaccessfile object is at the beginning of the file, and after each read and write operation, the pointer to the file position is moved to the read-write byte; the Getfilepointer () method to obtain the location of the file position pointer, and the Seek method to set the location of the file pointer.--[$] Random IO access--Package Org.susan.java.io;
Import java.io.IOException; Import Java.io.RandomAccessFile;
Public Class randomioapp {    public static void main (string args[])  throws  ioexception{        randomaccessfile file = new randomaccessfile ("D :/test.txt ", rw");         file.writeboolean (true);         file.writeint (123456);         file.writechar (' J ');         file.writedouble (1234.56);         file.seek (1);         system.out.println (File.readint ());         system.out.println (File.readchar ());         system.out.println (file.readdouble ());         file.seek (0);         system.out.println (File.readboolean ());         file.close ();    &nbsp}} The output of this code is: 123456 J 1234.56 true more than that, the contents of the Test.txt file were written, and I made a small mistake in writing the program that the first File.seek (1) was not invoked, so the first time it ran, it threw a eofexception, Because the file's cursor does not move to the front, the default is to have no bytes to read. A simpler example is provided below to illustrate the use of this class."*: here to apologize to the reader, because I do not know how to describe this class, can only use simple to operate, this is my personal level of problem, because sometimes only use this class, and not use a lot. "    --[$] Another simple usage--Package Org.susan.java.io;
Import Java.io.RandomAccessFile;
Public Class randomaccessfilemain {    public static void main (string args[])   throws exception{        randomaccessfile file = new randomaccessfile ("D:/test.html", "RW");         for ( int i = 0; I <= 6; i++) {        &n bsp;   system.out.println (File.readline ());         }         long current = File.getfilepointer ();         file.seek (current + 0);         file.write ("GetBytes" ());         for ( int i = 0; I <= 6; i++) {        &n bsp;   system.out.println (File.readline ());                  current = File.getfilepointer ();        &NBsp;file.seek (current + 6);         file.write ("GetBytes" ());         file.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.