Common methods and examples of Java file class

Source: Internet
Author: User
Tags parent directory

Create:
CreateNewFile () Creates an empty file at the specified location, returns True if it already exists, and then returns false.
mkdir () creates a single-level folder at the specified location.
Mkdirs () creates a multilevel folder at the specified location.
Renameto (file dest) if the target file and the source file is under the same path, then the role of Renameto is to rename, if the target file and the source file is not the same path, then the role of Renameto is cut, and can not manipulate the folder.

Delete:
Delete () deletes a file or an empty folder, cannot delete a non-empty folder, deletes the file immediately, and returns a Boolean value.
Deleteonexit () When the JVM exits, delete files or folders to delete temporary files, no return values.

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.
Boolean CanExecute () determines whether the file is executable
Boolean CanRead () to determine if the file is readable
Boolean canWrite () to determine if the file is writable

Get:
GetName () Gets the name of the file or folder and does not contain the ancestor path.
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), returns 0 if the file does not exist, and returns 0 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:
Static 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.
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.
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 (FilenameFilter filter) returns a sub-file or subdirectory that specifies the filter criteria in the current directory. For files such operations will return NULL.



Example ********************


Import Java.io.File;

1. Create a file in the specified location Creatnewfile ()
File MyFile = new file ("D:\\test.txt");
if (!myfile.exists) {
Myfile.mkdir ();//Create Folder

Myfile.creatnewfile (); Create a file
}


2. Create a folder at the specified location mkdir ()
File MyFile = new file ("D:\\yxy");
if (!myfile.exists) {
Myfile.mkdir ();//Create Folder
}

3. Create a multilevel folder at the specified location mkdirs ()
File MyFile = new file ("D:/yxy");
if (!myfile.exists) {
If the parent directory exists, the subdirectory is created directly in the parent directory, and if the parent directory does not exist, all directories are created recursively
Myfile.mkdirs ();
}



4. Use recursion to traverse the directory:
public class Test2 {

public static void Main (string[] args) {
Myfile yxy=new Myfile ();
Yxy.yxyfile ();
}
}
Class myfile{
File MyFile = new file ("D:/yxy");
File[] Files=myfile.listfiles ();
void Yxyfile () {
for (File fd:files) {
if (Fd.isdirectory ()) {
System.out.println (FD);
Files =fd.listfiles ();//Generate New Listfiles ()
Yxyfile ();//Use recursion
}else{
System.out.println (FD);
}
}
}


5. Empty all folders and files in the directory
① Method One:
public class Test2 {

public static void Main (string[] args) {
Myfile yxy=new Myfile ();
Yxy.yxyfile ();
}
}
Class myfile{
File MyFile = new file ("D:/yxy");
File[] Files=myfile.listfiles ();
void Yxyfile () {
The first for loop to delete a file
Arraylist<file> dirname=new arraylist<file> ();//For saving directories
for (File fd:files) {
if (Fd.isdirectory ()) {
System.out.println (FD);
Files =fd.listfiles ();//Generate New Listfiles ()
Dirname.add (FD);
Yxyfile ();//Use recursion
}else{
System.out.println (FD);
Fd.delete ();//Delete all Files
}
Delete Empty Directory
for (File dir:dirname) {
Dir.delete ();
}}}}

② Method Two:
public class Test2 {

public static void Main (string[] args) {
Myfile yxy=new Myfile ();
Yxy.yxyfile ();
}
}
Class myfile{
File MyFile = new file ("D:/yxy");
File[] Files=myfile.listfiles ();
void Yxyfile () {
The first for loop to delete a file
for (File fd:files) {
if (Fd.isdirectory ()) {
System.out.println (FD);
Files =fd.listfiles ();//Generate New Listfiles ()
Yxyfile ();//Use recursion
}else{
System.out.println (FD);
Fd.delete ();//Delete all Files
}
Delete Empty Directory
File[] Dir=myfile.listfiles ();//The remaining empty folder
for (int i=0;i<dir.length;i++) {
Dir[i].delete ();
}}}}

③ method Three (call cmd, simple):
public class Test1 {

public static void Main (string[] args) {
try {
String cmd = "cmd.exe/c rd/s/q e:\\yxy";
Runtime.getruntime (). exec (CMD);
SYSTEM.OUT.PRINTLN ("yes");
} catch (Exception e) {
System.out.println ("Error");
} }}

Note:/s represents the deletion of all subdirectories and subdirectories of the file,/Q for deletion without the need for confirmation,

The difference between 6.list () and Listfiles ()
File File=new file ("E:\\xxx");
String[] Filename1=file.list ();//Returns the name of the file or directory
File[] Filename2=file.listfiles ();//returns the full path of a file or directory
File[] Filename3=file.listroots ();//list all the root directories (window is the drive letter for all systems)
for (String name1:filename1) {System.out.println (name1);}
for (File name2:filename2) {System.out.println (name2);}
for (File Name3:filename3) {System.out.println (name3);}

Output:
List ():
Python built-in conversion method. png
Python's object-oriented. png
New Folder

Listfiles ():
E:\xxx\python built-in conversion method. png
E:\xxx\python object-oriented. png
E:\xxx\ new Folder

Listroots ():
C +
D:\
E:\
Z:\

7.renameTo (File dest)
Note: If the target file is under the same path as the source file, then Renameto is renamed if the destination file is not in the same path as the source file

, then the Renameto function is cut, and cannot manipulate the folder.

① Rename:
File File=new file ("E:\\xxx\\python object-oriented. png");
File.renameto ("E:\\xxx\\py object-oriented. png"));

② Moving files:
File File=new file ("E:\\xxx\\python object-oriented. png");
File.renameto ("D:\\python object-oriented. png"));

8. Call the cmd command to move the entire folder
try{
Runtime.getruntime (). EXEC ("cmd.exe/c move e:\\xxx\\1 E:");
}catch (Exception e) {
System.out.println ("Error");
}

Common methods and examples of Java file class

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.