Java about file Usage

Source: Internet
Author: User
Tags terminates

1. File Class1.1. File class Description

The data stored in variables , arrays, and objects is temporary and they are lost when the program terminates. In order to be able to forever

long time to save the data created in the program, you need to store them in a file on your hard disk or disc. These files can be moved, transmitted, or used by other programs. Because the data is stored in a file, we need to learn a class that is closely related to files, called the file class, You will be mastering the properties of getting files and deleting and renaming files. Finally, how to write data to a file and read data from a file.

so The file class is concerned with the storage of files on disk.

The file class describes a document or folder. (folders can also be called directories)

The appearance of this class is the encapsulation of objects in files and folders in the file system. You can manipulate files and folders through the idea of objects.

Can use object-oriented processing problems, through the method of the object, you can get the information of the file or folder to facilitate the operation of the file and folder property information.

The file contains a lot of information , such as file name, creation modification time, size, readable writable property, and so on.

1.2. Experience the file class

verifies whether the specified directory or file exists under the specified path .

Verifies whether the specified directory or file exists under the specified path.

File File = new file ("C:\\a.txt");

System. out. println (File.exists ());

Whether the file object is a directory

System. out. println (File.isdirectory ());

Whether the object is a file

System. out. println (File.isfile ());

Conclusion: The file object can also represent files that do not exist. Actually represents an abstract path.

Build a An instance of the file class does not create a file on the machine. You can create a file instance of an arbitrary file name, regardless of whether it exists, or you can call the Exists method of the file instance to determine if the files or directories exist

1.3. Constructs an instance of a file class:

New File (String pathname);

Creates a new file instance by the given path.

New File (string parent, string child);

Creates a new file instance based on the parent pathname string and the child pathname.

The parent refers to the path to the parent directory, and the full path is parent+child.

New file (file parent, String child);

Creates a new file instance based on the parent abstract pathname and child pathname.

The parent refers to the path to the parent directory, and the complete path is Parent.getpath () +child.

Description

If the specified path does not exist (without this file or folder), the exception is not thrown, and file.exists () returns false.

New File Object file File=new file ();

Public Static void Main (string[] args) {

file file = new file();

}

1: Create File object requires guide, import java.io.File

The 2:file object does not have parameterless constructs. The creation of an object requires a reference.

according to The API documentation prompts you to pass in a string path to a file. String path= "C:/a.txt";

(The A.txt file already exists under C disk)

File is a Document object

String Path = "C:/a.txt";

File File = new file (path);

The object of the file class, which can either represent a file or represent a folder.

Public Static void Main (string[] args) {

File is a folder

String Path = "C:/test";

File File = new file (path);

}

1.4. Path:

The path is where the file or folder resides.

1.4.1. Path Separator:

Use separators to separate the subordinate folders:

in the The delimiter in Windows is ' \ ', in Unix/linux the delimiter is '/'.

Cross-platform directory separators

A more professional approach is to use File.separatorchar, this value will be based on the system's corresponding delimiters.

Example:new File ("C:" + File.separatorchar + "a.txt");

Note that if "\" is used, it needs to be escaped, written as "\ \", and if it is two "\", it is written as "\\\\".

Experiment:

Try to write a different path in the following code, and observe the output.

File File = new file (path);

System.out.println (File.getabsolutepath ());

1.4.2. absolute path vs. relative path:

for UNIX platform, the prefix for absolute pathname is "/". There is no prefix for relative path names.

for For Windows platforms, the prefix of the absolute pathname is composed of a drive letter and a ":", example "c:\\ ...". Relative paths do not have a drive letter prefix.

Relative path:

A relative path refers to a path relative to a location, which refers to the current directory.

in the execution Java program, the relative path is the current directory where Java commands are executed.

Experiment:

Execute the Java command under a different path to run the following program and observe the output.

File File = new file ("A.txt");

System.out.println (File.getabsolutepath ());

Generally in use, it is recommended to use absolute path, because the relative path is prone to problems, not sure where in the end.

Relative path

File File = new file ("src/a.txt");

1.5. common methods in the file class:

Create:

CreateNewFile () Creates an empty file at the specified location, returns True if it exists, does not create and then returns false

mkdir () Creates a directory at the specified location, which creates only the last level of the directory and throws an exception if the parent directory does not exist.

Mkdirs () Creates a directory at the specified location, which creates all directories that do not exist in the path.

Renameto (file dest) rename files or folders, you can also manipulate non-empty folders, the file is the same as the cut of the file, when the cut can not operate non-empty folders. The move/Rename succeeds returns True, and the failure returns false.

Delete:

Delete () deletes a file or an empty folder, if it is a folder and is not empty, it cannot be deleted, returns true successfully, and the failure returns false.

Deleteonexit () when the virtual machine terminates, requests that the file or directory represented by this abstract pathname be deleted, and that temporary files created when the program is abnormal can also be deleted

Judge:

Exists () whether the file or folder exists.

Isfile () is a file and is always false if it does not exist.

Isdirectory () is a directory and is always false if it does not exist.

Ishidden () Whether it is a hidden file or whether it is a hidden directory.

Isabsolute () tests whether this abstract path name is an absolute pathname.

Get:

GetName () Gets the name of the file or folder and does not contain the ancestor path.

GetPath () returns an absolute path, which can be a relative path, but the directory is specified

GetAbsolutePath () Gets the absolute path to the file, and it doesn't matter if the file exists

Length () Gets the size of the file (in bytes) and returns 0L if the file does not exist, and returns 0L if it is a folder.

GetParent () returns the pathname string of the parent directory for this abstract pathname, or null if the pathname does not specify a parent directory.

LastModified () Gets the last time it was modified.

Folder-Related:

Staic file[] Listroots () lists all the root directories (in window is the drive letter for all systems)

List () returns the file or directory name in the directory containing the hidden file. For files such operations will return NULL.

The list (FilenameFilter filter) returns a sub-file or subdirectory that specifies the filter criteria in the current directory. For files such operations will return NULL.

Listfiles () returns a file or directory object (instance of the file class) in the directory that contains the hidden file. For files such operations will return NULL.

Listfiles (FilenameFilter filter) returns a sub-file or subdirectory that specifies the filter criteria in the current directory. For files such operations will return NULL.

1.6. Case:

1, lists all sub-filenames and all subdirectory names in the specified directory.

2, listing all sub-filenames and all subdirectory names in the specified directory, requiring directory names to be listed separately from file names, in the following format:

Sub-directories:

...

...

Sub-file:

...

...

3, lists all files in the specified directory that have the. java extension.

4, lists all files in the specified directory that have the. class extension.

5, thinking about the 3rd and 4th, the code is not repeating it, if you want to list all of the. txt files, do you want to write another class?

A, please design a tool method, you can pass the specified extension, the tool method will be listed in the specified directory in the specified extension of all sub-files and subfolders.

b, use the FilenameFilter interface to write a tool class that can pass the specified filtering rules.

6, List all descendants and descendants directory names in the specified directory, just list the names.

Problem Solving : Lists all sub-filenames and all subdirectory names in the specified directory.

Requirement 1: Get all the files and folders in the C:/test-Test directory

Problem Solving Ideas:

The code needs to be encapsulated, and the method needs to be created and called and tested in the main method. Method name to make sense: listallfilesanddirs

First step: Create a File object

Step two: Find the methods available in the file class and want to get all the sub-files and subdirectories under that directory

Step three: Display the names of these files and folders

Implementation :

/**

* Lists all included sub-files and subdirectories in the specified directory

*/

Public Static void listallfilesanddirs (String path) {

1. Create a File object that represents this directory

File dir = new file (path);

2. Get all the subdirectories and sub-file names contained by the list method

string[] names = Dir.list ();

3 Show these names

for (int i = 0; i < names.length; i++) {

System. out. println (Names[i]);

}

}

Problem Solving : Lists all sub-filenames and all subdirectory names in the specified directory, requiring directory names to be listed separately from file names

Case 1 lists the files and folders, but cannot distinguish between files and folders.  The file class has methods for judging files and folders, but the list method returns a string array, and the list () method does not meet our needs. Continue to find the method for file. View API find file[] Listfiles () The method is found to return a file array.

Ideas:

First step: Create the Listallfilesanddirs (String path) method, accept the path

Step Two: Create a File object to represent this directory

Step three: Get all the subdirectories and sub-file names contained by the Listfiles method

Fourth step: Get all the file name collections, with all the folder names set

Fifth Step: Display the file name and folder name respectively

Realize

Public Static void listAllFilesAndDirs2 (String path) {

1. Create a File object that represents this directory

File dir = new file (path);

2 All subdirectories and sub-file names that are contained by the Listfiles method

file[] names = Dir.listfiles ();

3, display file name and folder name, respectively

for (int i = 0; i < names.length; i++) {

File file = Names[i];

if (File.isfile ()) {

System. out. println (("Sub-File:"));

System. out. println ("\ T" + file.getname ());

} Else if (File.isdirectory ()) {

System. out. println (("Sub-Directory:"));

System. out. println ("\ T" + file.getname ());

}

}

}

implementation two :

Public Static void listallfilesanddirs (String path) {

1 Create a File object to represent this directory

File dir = new file (path);

2 All subdirectories and sub-file names that are contained by the Listfiles method

file[] names = Dir.listfiles ();

3, get all the file names collection, with all the folder names set

list<file> fileslist = new arraylist<file> ();

list<file> dirslist = new arraylist<file> ();

for (int i = 0; i < names.length; i++) {

File file = Names[i];

if (File.isfile ()) {

Fileslist.add (file);

} Else if (File.isdirectory ()) {

Dirslist.add (file);

}

}

4, display file name and folder name, respectively

System. out. println ("sub-file:");

for (int i = 0; i < fileslist.size (); i++) {

System. out. println ("\ T" + fileslist.get (i). GetName ());

}

System. out. println ("Sub-Directory:");

for (int i = 0; i < dirslist.size (); i++) {

System. out. println ("\ T" + dirslist.get (i). GetName ());

}

}

Exercise 3 lists all files in the specified directory that have the. java extension.

Requirement: Locate the file with the specified extension from the specified directory and list it.

Ideas

First step: Create the Lsitallfiles method, accept the path and file suffix name

Step two: Get all the sub-files and subfolders

Step three: Find the eligible files and show them

Note: Windows systems with different systems for paths use slashes as path separators "\" Linux systems use backslashes as path separators "/" Java is a cross-platform language, Java programs if deployed to Linux system, if the program has File object, you can use the file class Separatorchar (field)

Public class FileTest2 {

Public Static void Main (string[] args) {

String path = "C:" + File. Separatorchar + "test";

File File = new file (path);

Listtallfiles (File, "Java");

}

/**

* Locate the file with the specified extension from the specified directory and list it.

*

*/

Public Static void listtallfiles (File dir, String extension) {

1. Get all sub-files and subfolders

file[] files = dir.listfiles ();

2. Identify the eligible files and show them

for (int i = 0; i < files.length; i++) {

File file = Files[i];

3. You need to specify the end of the file suffix to calculate the eligible

if (File.getname (). EndsWith (extension)) {

System. out. println (File.getname ());

}

}

}

}

Exercise 4:

Public class FileTest2 {

Public Static void Main (string[] args) {

String path = "C:" + File. Separatorchar + "test";

File File = new file (path);

ListtAllFiles2 (File, "txt");

}

/**

* FilenameFilter Interface Write a tool class that can pass the specified filter rules.

* Locate the file with the specified extension from the specified directory and list it.

*

* */

Public Static void listtAllFiles2 (File dir, String name) {

1. Get all sub-files and subfolders

string[] files = dir.list (new dirfilter ("txt"));

2 Display Name

for (int i = 0; i < files.length; i++) {

System. out. println (Files[i]);

}

}

}

class Dirfilter implements FilenameFilter {

Private String extension;

Public Dirfilter () {

}

Public Dirfilter (String extension) {

this. Extension = extension;

}

@Override

Public Boolean Accept (File dir, String name) {

return name.endswith (extension);

}

}

Note : Dirfilter is the implementation of the Accept method. The list method that is provided to the file class is used.

Java about file Usage

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.