Java File Action File Class

Keywords: Java Android Windows Linux

1. Learning Contents

File operations using the File class, using the Java.io package to complete a total of five core classes and an interface

  • Five core interfaces: File, InputStream, OutputStream, Reader, Writer
  • One identity interface: Serializable

1. Create Documents
2. Create files with subdirectories
3. Obtaining the Contents of Documents
4. Summary

2. Specific Contents

2.1 Create Files

Within the entire java.io package, the File class is the only class related to the operation of the file itself, but it does not involve the specific contents of the file. The file itself refers to the creation and deletion of the file.

To use the File class, you first need to define the file path to operate on through the methods he provides.

  • Set the full path: public File(String pathname)
  • Set parent and child file paths: public File(File parent, String child) (Android)
  • Create file: public boolean createNewFile() throws IOException
    |--------------- If the directory is not accessible;
    |----------------- If the file name is the same or the file name is incorrect;
  • Delete file: public boolean delete()
  • Judging existence: public boolean exists()

Example: Sample code

 public class Test2 {
	public static void main(String args[]) throws Exception{
		File file = new File("E:\\sublimefile\\test.txt"); // Set File Path
		If (file.exists()) { // File Exists
			file.delete();
		} else {
			System.out.println(file.createNewFile());
		}
	}
}

The above program can already complete the creation of specific files, there are two problems at this time.

  • The following are supported in Windows: the'\'path separator, while Linux uses the'/' path separator;
    |---------- A constant is provided in the File class: public static final String separator

But the code looks a little long

File file = new File("E:" + File.separator +  "sublimefile" + File.separator + "test.txt"); // Set File Path
  • Delays occur during java.io operations, because the problem now is that Java programs perform file operations indirectly through the file system's file processing functions through the JVM, so there is a delay in between.

2.2 Create files with subdirectories

You've already created the file above, but this time it's created directly under the root path. Here's how to create the file with subdirectories

File file = new File("E:" + File.separator +  "sublimefile" + File.separator + "demo" + File.separator + "test.txt"); // Set File Path
  • Since the "demo" directory does not exist, the system will assume that the path is unusable at this time, and it is time to determine if the parent path exists.
    • Find the parent path: public File getParentFile();
    • Create a multilevel directory (parent path): public boolean mkdirs()

Code example:

public class Test2 {
	public static void main(String args[]) throws Exception{
		File file = new File("E:" + File.separator +  "sublimefile" + File.separator 
				+ "hello" +File.separator + "demo" + File.separator + "test.txt"); // Set File Path
		System.out.println(file.getParentFile().exists());
		If (! file.getParentFile().exists()) { // Parent path does not exist
			file.getParentFile().mkdirs(); // Create Parent Path
		}
		If (file.exists()) { // File Exists
			file.delete();
		} else {
			System.out.println(file.createNewFile());
		}
	}
}

2.3 Get the contents of the file

Within the File class, there is a series of operations to get the contents of the file information:

  • Get the file size: public long length(), returned in bytes;

  • Determine if it is a file: public boolean isFile();

  • Determine if it is a directory: public boolean isDirectory();

  • Last modified date: public long lastModified();

Code example:

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test2 {
	public static void main(String args[]) throws Exception {
		File file = new File("E:" + File.separator + "jpg.jpeg");
		if (file.exists()) {
			System.out.println("Is it a file:" + (file.isFile()));
			System.out.println("Is it a directory:" + (file.isDirectory()));
			System.out.println("File size:" + new BigDecimal((double) file.length() / 1024 / 1024).divide(new BigDecimal(1),
					2, BigDecimal.ROUND_HALF_UP) + "M");
			System.out.println("Last Modified Time" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(file.lastModified())));
		}
	}
}


The information about the file retrieved throughout the retrieval process, but does not contain the contents of the file.

  • But the entire disk contains directories in addition to files, so the most common function for directories is to list the composition of directories. In the File class, there are two ways to list directories:
    • List the information under the directory: public String[] list()
    • List all information for File class wrapper: public String[] list(FilenameFilter filter)

Code example:

 public class Test2 {
	public static void main(String args[]) throws Exception {
		File file = new File("E:" + File.separator);
		if (file.isDirectory()) { // A path given now
			String[] result = file.list();
			for (int x = 0; x < result.length; x++) {
				System.out.println(result[x]);
			}
		}
	}
}

  • Although you can list directories at this point, the objects listed are subdirectories under the directory or file names that list the File class

Code example:

public class Test2 {
	public static void main(String args[]) throws Exception {
		File file = new File("E:" + File.separator);
		if (file.isDirectory()) { // A path given now
			File[] result = file.listFiles();
			for (int x = 0; x < result.length; x++) {
				System.out.println(result[x]);
			}
		}
	}
}

Here's what happened: It's different

To better experience the benefits of these operations, the following output is a resource manager-like interface.

Sample code (similar to Resource Manager):

public class Test2 {
	public static void main(String args[]) throws Exception {
		File file = new File("E:" + File.separator);
		if (file.isDirectory()) { // A path given now
			File[] result = file.listFiles();
			for (int x = 0; x < result.length; x++) {
				System.out.println(result[x].getName() + "\t\t\t" 
			+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
			.format(new Date(result[x].lastModified())) + "\t\t" 
			+ (result[x].isDirectory() ? "Folder":"file") 
			+ new BigDecimal((double) result[x].length() / 1024 / 1024).divide(new BigDecimal(1),
					2, BigDecimal.ROUND_HALF_UP) + "M");
			}
		}
	}
}


Serial validation reveals that it is easier to get a list of objects because you can continue with the list.
Think Question: List all subdirectories in a given directory

Principle: If a directory is still given, all its components should be listed and done recursively.

Code example (listing all subdirectories under the specified directory):

public class Test2 {
	public static void main(String args[]) throws Exception {
		File file = new File("E:" + File.separator );
		print(file);
	}
	public static void print(File file) {
		if (file.isDirectory()) {  // If a path is given now
			File[] result = file.listFiles(); // List subdirectories
			if (result != null) {
				for (int x = 0; x < result.length; x++) {
					print(result[x]);
				}
			}
		}
		System.out.println(file);
	}
}

If the above output operation is replaced by a delete operation, it will become a malignant program.

3. Summary

  1. The File class itself only operates on files and does not involve content.

  2. Important methods in File:

    * Set the full path: public File(String pathname);
    *Delete file: public boolean delete();
    *Determine if the file exists: public boolean exists()
    *Find the parent path: public File getParentFile();
    * Create a directory: public boolean mkdir();

  3. The path separator is used when using File class operations: File.separator;

Posted by dannynosleeves on Sat, 03 Aug 2019 19:58:31 -0700