The file class in Java and the FileDescriptor document description class _java

Source: Internet
Author: User
Tags comparable mkdir parent directory

File

File is an abstract representation of files and directory path names.
File directly inherits from object and implements the serializable interface and the comparable interface. Implementing the Serializable interface means that the file object supports serialization operations. The implementation of the comparable interface means that the file object can be compared to size, file can be stored directly in an ordered set (such as TreeSet, TreeMap).
1. Common ways to create a new catalog
Method 1: Create a new directory based on relative paths.
The sample code is as follows (new directory "dir" under the current path):

File dir = new file ("dir");
Dir.mkdir ();

Method 2: Create a new directory based on Absolute path.
The sample code is as follows (new directory "/home/skywang/dir"):

File dir = new file ("/home/skywang/dir");
Dir.mkdirs ();

Description: Above is the Linux system under the new directory "/home/skywang/dir" source. Under Windows, to create a new directory of "D:/dir", the source code is as follows:

File dir = new file ("D:/dir");
Dir.mkdir ();

Method 3

Uri uri = new Uri ("File:/home/skywang/dir"); 
File dir = new file (URI);
Sub.mkdir ();

Description: Similar to Method 2, except that the full path is passed in "Method 2", and the full path corresponding URI is passed in "Method 3".
2. Several common methods of new subdirectories
For example, we want to create a new subdirectory under subdirectory "dir" in the current directory. There are several ways:
Method 1

File Sub1 = new file ("dir", "Sub1");
Sub1.mkdir ();

Description: The above method action is, in the current directory "Dir/sub1". The premise of its normal operation is "SUB1" The Parent Directory "DIR" already exists!
Method 2

File Sub2 = new file (dir, "Sub2");
Sub2.mkdir ();

Description: The above method action is, in the current directory "DIR/SUB2". The premise of its normal operation is "SUB2" The Parent Directory "DIR" already exists!
Method 3

File Sub3 = new file ("Dir/sub3");
Sub3.mkdirs ();

Description: The above method action is, in the current directory "Dir/sub3". It does not require that Dir already exists, and that it works correctly, and that the Mkdirs () method automatically creates the parent directory if the "SUB3" parent path does not exist.
Method 4

File SUB4 = new file ("/home/skywang/dir/sub4");
Sub4.mkdirs ();

Description: The above method function is to create a new directory "/home/skywang/dir/sub3". It does not require that Dir already exists, and that it works correctly, and that the Mkdirs () method automatically creates the parent directory if the "SUB4" parent path does not exist.
Method 5

Uri uri = new Uri ("File:/home/skywang/dir/sub5"); 
File SUB5 = new file (URI);
Sub5.mkdirs ();

Description: Similar to Method 4, except that the full path is passed in "Method 4", and the full path corresponding URI is passed in "Method 5".
3. Several common methods of creating new files
For example, we want to create a new file under subdirectory "dir" in the current directory. There are several ways
Method 1

try {
  file dir = new File ("dir");  Gets the file object
  file File1 = new file (dir, "file1.txt") corresponding to the directory "dir";
  File1.createnewfile ();
} catch (IOException e) {
  e.printstacktrace ();
}

Description: The above code function is to create a new file "File1.txt" under the "dir" directory (relative Path).
Method 2

try {
  file File2 = new file ("dir", "File2.txt");
  File2.createnewfile ();
} catch (IOException e) {
  e.printstacktrace ();
}

Description: The above code function is to create a new file "File2.txt" under the "dir" directory (relative Path).
Method 3

try {
  file File3 = new file ("/home/skywang/dir/file3.txt");
  File3.createnewfile ();
} catch (IOException e) {
  e.printstacktrace ();
}

Description: The above code function is, the next new file "/home/skywang/dir/file3.txt" (absolute path). This is based on the absolute path method under Linux, under Windows you can create a new file "D:/dir/file4.txt" with the following code.

try {
  file File3 = new file ("D:/dir/file4.txt");
  File3.createnewfile ();
} catch (IOException e) {
  e.printstacktrace ();
}

Method 4

Try {
  uri uri = new URI ("File:/home/skywang/dir/file4.txt"); 
  File File4 = new file (URI);
  File4.createnewfile ();
} catch (IOException e) {
  e.printstacktrace ();
}

Description:
is similar to Method 3, except that the full path is passed in "Method 3" and the full path corresponding URI is passed in "Method 4".
4. The file API uses the example
for detailed usage of the API in File, reference sample code (FILETEST.JAVA):

Import Java.io.File;
Import java.io.IOException;
Import Java.net.URI;
Import Java.util.Calendar;

Import Java.text.SimpleDateFormat;
  public class Filetest {public static void main (string[] args) {testfilestaticfields ();
  Testfiledirapis (); public static void Testfilestaticfields () {//print path separator: System.out.printf ("file.pathseparator=\"%s\ "\ n", F
    Ile.pathseparator);
    Print path separator ': ' System.out.printf ("file.pathseparatorchar=\"%c\ "\ n", File.pathseparatorchar);
    Print separator "/" System.out.printf ("file.separator=\"%s\ "\ n", file.separator);
  Print separator '/' System.out.printf ("file.separatorchar=\"%c\ "\ n", File.separatorchar);
    public static void Testfiledirapis () {try {//new directory "dir" file dir = new file ("dir");

    Dir.mkdir (); Method 1: Create a new directory "Dir/sub1".
    The parent directory "DIR" must already exist!
    File Sub1 = new file ("dir", "sub1");
    Sub1.mkdir (); Method 2: Create a new directory "Dir/sub2".
    The parent directory "DIR" must already exist!
    File Sub2 = new file (dir, "sub2");
  Sub2.mkdir ();  Method 3: Create a new directory "Dir/sub3".
    Mkdirs () automatically creates a Non-existent parent directory.
    File Sub3 = new file ("Dir/sub3");
    Sub3.mkdirs (); Method 4: Create a new directory "Dir/sub4".
    Based on the "absolute path", the first 3 methods are created according to the relative path.  String Dirpath = Dir.getabsolutepath ();  Gets the absolute path of "dir" String Sub4abspath = dirpath + file.separator + "SUB4";
    File.separator is the delimiter "/" File Sub4 = new file (Sub4abspath);
    Sub4.mkdirs (); Method 5: Create a new directory "DIR/SUB5".
    According to the URI String uri_sub5_path = "File:" + Dirpath + file.separator + "SUB5"; 
    Uri uri_sub5 = new Uri (Uri_sub5_path);
    File SUB5 = new file (URI_SUB5);

    Sub5.mkdirs ();
    Method 1: New file "dir/l1_normal.txt" filename = L1_normal = new (dir, "L1_normal.txt");
    L1_normal.createnewfile ();
    Method 2: New File "Dir/.l1_hide.txt". File L1_hide = new file ("dir", ". L1_hide.txt"); In Linux, "."
    The file that starts with is a hidden file.
    L1_hide.createnewfile ();
    Method 3: New File "Dir/l1_abs.txt".  String Dirabspah = Dir.getabsolutepath ();
    Get dir's absolute path String L1_abs_path = dirabspah+file.separator+ "L1_abs.txt"; FiLe l1_abs = new File (L1_abs_path);
    L1_abs.createnewfile ();
    System.out.printf ("l1_abs_path=%s\n", L1_abs_path);
    System.out.printf ("L1_abs path=%s\n", L1_abs.getabsolutepath ()); Method 4: New File "Dir/l1_uri.txt".
    New file based on URI String Uri_path = "File:" + Dirabspah + file.separator + "L1_uri.txt"; 
    Uri uri_l1 = new Uri (Uri_path);
    System.out.printf ("uri_l1=%s\n", L1_abs.getabsolutepath ()); 
    File L1_uri = new file (URI_L1);

    L1_uri.createnewfile ();
    The new file, "Dir/sub/s1_normal", is "file S1_normal = new" (Sub1, "s1_normal.txt");

    S1_normal.createnewfile ();
    System.out.printf ("%30s =%s\n", "s1_normal.exists ()", s1_normal.exists ());
    System.out.printf ("%30s =%s\n", "S1_normal.getname ()", S1_normal.getname ());
    System.out.printf ("%30s =%s\n", "s1_normal.getparent ()", s1_normal.getparent ());
    System.out.printf ("%30s =%s\n", "S1_normal.getpath ()", S1_normal.getpath ()); System.out.printf ("%30s =%s\n", "S1_normal.getabsolutepath ()", S1_norMal.getabsolutepath ());
    System.out.printf ("%30s =%s\n", "S1_normal.getcanonicalpath ()", S1_normal.getcanonicalpath ()); System.out.printf ("%30s =%s is \"%s\ "\ n", "s1_normal.lastmodified ()", s1_normal.lastmodified (), Getmodifytime (s1_
    Normal.lastmodified ()));


    System.out.printf ("%30s =%s\n", "S1_normal.touri ()", S1_normal.touri ());
    Lists the files and folders under the Dir directory.
    Note: Dir.listfiles () will only traverse directory dir, not the subdirectory of Dir!
    SYSTEM.OUT.PRINTLN ("----list files and folders----");
    file[] fs = Dir.listfiles ();
      for (File f:fs) {String fname = F.getname (); String absstr = F.isabsolute ()?
      "[Absolute]": "; String hidstr = F.ishidden ()?
      "[Hidden]": "; String dirstr = F.isdirectory ()?
      "[Directory]": "; String filestr = F.isfile ()?

      "[File]": ";
    System.out.printf ("%-30s%s%s%s%s\n", fname, Filestr, Dirstr, Absstr, HIDSTR);
    } catch (Exception e) {e.printstacktrace (); private static String Getmodifytime (longMillis) {//Get calendar object Calendar cal = Calendar.getinstance ();
    The setting time is Millis Cal.settimeinmillis (Millis);
    Gets the formatted object, which simpledateformat the SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss") according to the YYYY-MM-DD HH:mm:ss format date;
    System.out.printf ("Time%s\n", str); 
  Return Sdf.format (Cal.gettime ());

 }

}

Run results (running results under the Ubuntu 12.04 system, not windows! ):

File.pathseparator= ":" file.pathseparatorchar= ":" file.separator= "/" file.separatorchar= "/" s1_normal.exists () = TR UE s1_normal.getname () = S1_normal.txt s1_normal.getparent () = Dir/sub1 S1_normal.getpath () = Dir/sub1/s1 _normal.txt S1_normal.getabsolutepath () =/home/skywang/wind_talker/workout/java/skywang/io/io/src/file/dir/sub1/ S1_normal.txt S1_normal.getcanonicalpath () =/home/skywang/wind_talker/workout/java/skywang/io/io/src/file/dir/ Sub1/s1_normal.txt s1_normal.lastmodified () = 1381730064000 is "2013-10-14 13:54:24" s1_normal.touri () = file:/h
Ome/skywang/wind_talker/workout/java/skywang/io/io/src/file/dir/sub1/s1_normal.txt----List files and folders----              l1_uri.txt [file] sub1 [directory] l1_abs.txt [file] sub5 [directory] Sub4 [Directory]. l1_hide.txt [File][hidden] sub3 [directory] sub2 [directory] L
 1_normal.txt [File]

Results Note: When you run the program, the Directory "dir" and its subdirectories and subfolders are created in the directory where the source files are located. The following figure:

FileDescriptor

FileDescriptor is a "file descriptor".
FileDescriptor can be used to indicate open files, open sockets, and so on.
In the case of FileDescriptor: When FileDescriptor represents a file, we can generally think of filedescriptor as the file. However, we cannot manipulate the file directly via FileDescriptor, and if we need to operate the file through FileDescriptor, we need to create a new filedescriptor corresponding FileOutputStream and then manipulate the file.
In, out, Err introduction
(1) in--standard input (keyboard) descriptor
(2) out--standard output (screen) descriptor
(3) Err--Standard error output (screen) descriptor
The principles and usages of these 3 are similar, and we go through out to do a thorough study.
the function and principle of 1.1 out
out is a descriptor for the standard output (screen). But how does it work?
We can generally understand that out represents the standard output (screen). If we want to output the information to the screen, we can do it through out, but out does not provide an interface for outputting information to the screen (because the out nature is a FileDescriptor object and the FileDescriptor has no output interface). What do we do?
Quite simply, we create out corresponding "output stream objects" and then output the information to the screen via output interfaces such as write () of the output stream. The following code:

try {
  FileOutputStream out = new FileOutputStream (filedescriptor.out);
  Out.write (' A ');
  Out.close ();
} catch (IOException e) {
}

Executing the above program will output the letter ' A ' on the screen.
In order to facilitate our operation, Java has already packaged a "convenient interface for the output of information on the screen": Through System.out, we can easily output information to the screen.
Therefore, we can equivalently convert the above program to the following code:

System.out.print (' A ');

Here's how the above two pieces of code works
Look at the definition of out. It is defined in the Filedescriptor.java, the relevant source code is as follows:

Public final class FileDescriptor {

  private int fd;

  public static final FileDescriptor out = new FileDescriptor (1);

  Private FileDescriptor (int fd) {
    this.fd = FD;
    Usecount = new Atomicinteger ();
  }

  ...
}

From this, you can see
(1) Out is a FileDescriptor object. It is created by the constructor filedescriptor (int fd).
(2) The operation of FileDescriptor (int fd) is to assign a value to the FD object (type int) and create a new usecount using the Count variable.
FD object is a very important variable, "fd=1" on behalf of the "standard output", "fd=0" on behalf of the "standard input", "fd=2" represents the "standard error output."

FileOutputStream out = new FileOutputStream (filedescriptor.out);

is to use the constructor FileOutputStream (FileDescriptor fdobj) to create the filed.out corresponding FileOutputStream object.
about how System.out is defined. You can refer to "Understanding System.out.println" ("Hello World").
Through the above study, we know that we can customize the flow of standard file descriptors [i.e., in (standard input), out (standard output), ERR (standard error output)] To complete the input/output function; However, Java has encapsulated the corresponding interface for us, That is, we can more conveniently system.in, System.out, system.err to use them.
In addition, we can customize file descriptors such as "file", "Socket", and then manipulate them. Refer to the Testwrite (), Testread () interface in the example code below.
2. Sample code
The source code is as follows (Filedescriptortest.java):

Import Java.io.PrintStream;
Import Java.io.FileDescriptor;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;

Import java.io.IOException;
  public class Filedescriptortest {private static final String FileName = "file.txt";
  private static final String Outtext = "Hi filedescriptor";
    public static void Main (string[] args) {testwrite ();

    Testread ();
    TESTSTANDFD ();
  System.out.println (Outtext);
   /** * Filedescriptor.out TEST PROCEDURE * * The effect of the program is equivalent to SYSTEM.OUT.PRINTLN (Outtext); 
        * * private static void Teststandfd () {//create filedescriptor.out corresponding PrintStream printstream out = new PrintStream (
    New FileOutputStream (filedescriptor.out));
    Output "Hi filedescriptor" Out.println (outtext) on the screen;
  Out.close (); /** * FileDescriptor Write to sample program * * (1) To illustrate, "Create FileOutputStream by file name" is equivalent to the "Create FileOutputStream through File Descriptor" Object * (2
   The program creates a new file "File.txt" in the directory where "this source file" is located, and the contents of the file are "Aa".
* * private static void Testwrite () {try {      The new file "file.txt" corresponds to the FileOutputStream object FileOutputStream out1 = new FileOutputStream (FileName);
      Gets the file descriptor filedescriptor fdout = OUT1.GETFD () that corresponds to the document "File.txt";

      Create a "FileOutputStream" object based on the "file descriptor" FileOutputStream out2 = new FileOutputStream (fdout);  Out1.write (' A ');  Writing ' A ' out2.write (' a ') to "file.txt" by OUT1;

      Writes A ' A ' if (fdout!=null) System.out.printf ("Fdout (%s) is%s\n", Fdout ()) to "file.txt" by Out2;
      Out1.close ();

    Out2.close ();
    catch (IOException e) {e.printstacktrace (); }/** * FileDescriptor Read Sample program * * To illustrate, "Create FileInputStream by file name" and "Create FileInputStream by file descriptor" is equivalent to * * PR ivate static void Testread () {try {//new file ' file.txt ' corresponds to FileInputStream object fileinputstream = new in1
      Nputstream (FileName);
      Gets the file descriptor filedescriptor Fdin = IN1.GETFD () that corresponds to the document "File.txt"; Create a "FileInputStream" object based on the "file descriptor" FileInputStream in2 = new FileiNputstream (Fdin);
      System.out.println ("In1.read ():" + (char) in1.read ());

      System.out.println ("In2.read ():" + (char) in2.read ());

      if (fdin!=null) System.out.printf ("Fdin (%s) is%s\n", Fdin, Fdin.valid ());
      In1.close ();
    In2.close ();
    catch (IOException e) {e.printstacktrace ();

 }
  }
}

Run Result:

Fdout (Java.io.filedescriptor@2b820dda) is true
In1.read (): A
in2.read (): A
Fdin (java.io.FileDescriptor @675b7986) is true
Hi FileDescriptor

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.