File
File is an abstract representation of "file" and "directory pathname".
File is directly inherited from Object, implementing the Serializable interface and Comparable interface. Implementing the Serializable interface means that File objects support serialization operations. Implementing the Comparable interface means that File objects can be sized; Files can be directly stored in ordered sets (such as TreeSet and TreeMap).
1. Common methods for creating new directories
Method 1: Create a new directory based on the relative path.
The sample code is as follows (create the new directory "dir" under the current path):
File dir = new File("dir");dir.mkdir(); Method 2: Create a new directory based on the absolute path.
The sample code is as follows (create the new directory "/home/skywang/dir"):
File dir = new File("/home/skywang/dir");dir.mkdirs(); Note: The above is the source code of the new directory "/home/skywang/dir" under the linux system. Under Windows, if you want to create a new directory "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(); Note: Similar to "Method 2", except that the complete path is passed in "Method 2", while the full path is passed in "Method 3" is the URI corresponding to the full path.
2. Several common methods for creating a new subdirectory. For example, we want to create a new subdirectory under the subdirectory "dir" of the current directory. There are several ways:
Method 1
File sub1 = new File("dir", "sub1");sub1.mkdir(); Note: The function of the above method is to "dir/sub1" in the current directory. The premise for it to run normally is that the parent directory "dir" of "sub1" already exists!
Method 2
File sub2 = new File(dir, "sub2");sub2.mkdir();
Note: The function of the above method is to "dir/sub2" in the current directory. The premise for it to run normally is that the parent directory "dir" of "sub2" already exists!
Method 3
File sub3 = new File("dir/sub3");sub3.mkdirs(); Note: The function of the above method is to "dir/sub3" in the current directory. It does not require dir to exist and can run normally; if the parent path of "sub3" does not exist, the mkdirs() method will automatically create the parent directory.
Method 4
File sub4 = new File("/home/skywang/dir/sub4");sub4.mkdirs(); Note: The function of the above method is to create a new directory "/home/skywang/dir/sub3". It does not require dir to exist, and it can run normally; if the parent path of "sub4" does not exist, the mkdirs() method will automatically create the parent directory.
Method 5
URI uri = new URI("file:/home/skywang/dir/sub5"); File sub5 = new File(uri);sub5.mkdirs(); Note: Similar to "Method 4", except that the complete path is passed in "Method 4", while the complete path is passed in "Method 5" and the URI corresponding to the complete path is passed in.
3. Several common methods for creating new files
For example, we want to create a new file under the subdirectory of the current directory "dir". There are several methods 1
try { File dir = new File("dir"); // Get the File object corresponding to the directory "dir" File file1 = new File(dir, "file1.txt"); file1.createNewFile();} catch (IOException e) { e.printStackTrace();} Note: The function of the above code is to create a new file "file1.txt" in the "dir" directory (relative path).
Method 2
try { File file2 = new File("dir", "file2.txt"); file2.createNewFile();} catch (IOException e) { e.printStackTrace();} Note: The function of the above code is to create a new file "file2.txt" in the "dir" directory (relative path).
Method 3
try { File file3 = new File("/home/skywang/dir/file3.txt"); file3.createNewFile();} catch (IOException e) { e.printStackTrace();} Note: The function of the above code is to create a new file "/home/skywang/dir/file3.txt" (absolute path). This is a method based on the absolute path in Linux. In Windows, you can create a new file "D:/dir/file4.txt" through 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();} illustrate:
Similar to "Method 3", except that the complete path is passed in "Method 3", while the full path is passed in "Method 4" is the URI corresponding to the full path.
4. File API usage example
For detailed usage of APIs in File, refer to the example 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", File.pathSeparator); // Print path separator':' System.out.printf("File.pathSeparatorChar=/"%c/"/n", File.pathSeparatorChar); // Print delimiter"/" System.out.printf("File.separator=/"%s/"/n", File.separator); // Print delimiter'/' System.out.printf("File.separatorChar=/"%c/"/n", File.separator); // Print delimiter'/' System.out.printf("File.separatorChar=/"%c/"/n", File.separatorChar); } public static void testFileDirAPIS() { try { // Create new directory "dir" File dir = new File("dir"); dir.mkdir(); // Method 1: Create 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() will automatically create a parent directory that does not exist. File sub3 = new File("dir/sub3"); sub3.mkdirs(); // Method 4: Create a new directory "dir/sub4". Created according to "absolute path", the first 3 methods are created based on "relative path". String dirPath = dir.getAbsolutePath(); // Get 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 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: Create a new file "dir/l1_normal.txt" File l1_normal = new File(dir, "l1_normal.txt"); l1_normal.createNewFile(); // Method 2: Create a new file "dir/.l1_hide.txt". File l1_hide = new File("dir", ".l1_hide.txt"); // In linux, the file starting with "." is a hidden file. l1_hide.createNewFile(); // Method 3: Create a new file "dir/l1_abs.txt". String dirAbsPah = dir.getAbsolutePath(); // Get the absolute path of dir 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: Create a new file "dir/l1_uri.txt". Create a new file according to the 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(); // Create a new file "dir/sub/s1_normal" File s1_normal = new File(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()); // List "files" and "folders" in the "dir" directory. // Note: dir.listFiles() will only traverse the directory dir, not the subdirectories 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 hiddenStr = 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, hiddenStr); } } catch (Exception e) { e.printStackTrace(); } } private static String getModifyTime(long millis) { // Get Calendar object Calendar cal = Calendar.getInstance(); // Set the time to millis cal.setTimeInMillis(millis); // Get the formatted object, it will format the date according to "yyyy-MM-dd HH:mm:ss" SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //System.out.printf("TIME %s/n", str); return sdf.format(cal.getTime()); }} Running results (running results under ubuntu 12.04 system, not Windows!):
File.pathSeparator=":"File.pathSeparatorChar=":"File.separator="/"File.separatorChar="/" s1_normal.exists() = true 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:/home/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]l1_normal.txt [File]
Results: When running the program, a new directory "dir" will be created in the directory where the source file is located, its subdirectories and subfiles. As shown in the figure below:
FileDescriptor
FileDescriptor is a "file descriptor".
FileDescriptor can be used to represent open files, open sockets, etc.
To represent a file by FileDescriptor: When FileDescriptor represents a file, we can simply regard FileDescriptor as the file. However, we cannot operate on the file directly through FileDescriptor; if we need to operate on the file through FileDescriptor, we need to create a FileOutputStream corresponding to FileDescriptor and then operate on the file.
in, out, err introduction
(1) in -- descriptor for standard input (keyboard)
(2) out -- The descriptor for standard output (screen)
(3) err -- The descriptors of standard error output (screen) are similar in principle and usage. Let's conduct in-depth research through out.
1.1 The role and principle of out
out is the descriptor for standard output (screen). But what does it do?
We can understand it in a simple way that out represents standard output (screen). If we want to output information to the screen, we can operate it through out; however, out does not provide an interface to output information to the screen (because out is essentially a FileDescriptor object, and FileDescriptor does not have an output interface). What to do?
It's very simple. We create the "output stream object" corresponding to out, and then output the information to the screen through the output interface 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) {} Execute the above program and the letter 'A' will be output on the screen.
In order to facilitate our operation, Java has long encapsulated the "interface that can easily output information on the screen" for us: through System.out, we can easily output information to the screen.
Therefore, we can equivalently convert the above program into the following code:
System.out.print('A'); Let’s talk about the principles of the above two codes to see the definition of out. Its definition is in FileDescriptor.java, and 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, it can be seen that
(1) out is a FileDescriptor object. It is created through the constructor FileDescriptor(int fd).
(2) FileDescriptor(int fd) operation: assign values to the fd object (int type) and create a new count variable using useCount.
The fd object is a very important variable. "fd=1" represents "standard output", "fd=0" represents "standard input", and "fd=2" represents "standard error output".
FileOutputStream out = new FileOutputStream(FileDescriptor.out);
It is to use the constructor FileOutputStream(FileDescriptor fdObj) to create the "FileOutputStream object corresponding to Filed.out".
About how System.out is defined. You can refer to "In-depth understanding of System.out.println("hello world")"
Through the above learning, we know that we can customize the streams of standard file descriptors [i.e., in (standard input), out (standard error output), and err (standard error output)] to complete the input/output function; however, java has encapsulated the corresponding interface for us, that is, we can use System.in, System.out, System.err more conveniently.
In addition, we can also customize file descriptors for "file", "Socket", etc., and then operate on them. Refer to the testWrite(), testRead() and other interfaces in the following example code.
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); } /** * Test program of FileDescriptor.out* * The effect of this program is equivalent to System.out.println(OutText); */ private static void testStandFD() { // Create the corresponding PrintStream PrintStream out = new PrintStream( new FileOutputStream(FileDescriptor.out)); // Output "Hi FileDescriptor" on the screen out.println(OutText); out.close(); } /** * FileDescriptor writing sample program* * (1) To illustrate, "Creating FileOutputStream by file name" is equivalent to "Creating FileOutputStream by file descriptor" object* (2) The program will create a new file "file.txt" in the directory where "the source file" is located, and the file content is "Aa". */ private static void testWrite() { try { // Create FileOutputStream object corresponding to the file "file.txt" FileOutputStream out1 = new FileOutputStream(FileName); // Get the "file descriptor" corresponding to the file "file.txt" FileDescriptor fdout = out1.getFD(); // Create "FileOutputStream" object based on the "file descriptor" FileOutputStream out2 = new FileOutputStream(fdout); out1.write('A'); // Write 'A' to "file.txt" via out1 out2.write('a'); // Write 'A' to "file.txt" via out2 if (fdout!=null) System.out.printf("fdout(%s) is %s/n",fdout, fdout.valid()); out1.close(); out2.close(); } catch(IOException e) { e.printStackTrace(); } } /** * FileDescriptor read sample program* * To illustrate, "Create FileInputStream by file name" is equivalent to "Create FileInputStream by file descriptor" object*/ private static void testRead() { try { // Create FileInputStream object corresponding to the file "file.txt" FileInputStream in1 = new FileInputStream(FileName); // Get the "file descriptor" corresponding to the file "file.txt" FileDescriptor fdin = in1.getFD(); // Create "FileInputStream" object according to 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(); } }} Running results:
fdout(java.io.FileDescriptor@2b820dda) is truein1.read():Ain2.read():afdin(java.io.FileDescriptor@675b7986) is trueHi FileDescriptor