Common methods in the File class in java

Source: Internet
Author: User

This article has added a large number of frequently used methods in the File class in java. For more information, see.

1. Create
Boolean createNewFile (); create a file in the specified path. If the file already exists, do not create it. false is returned. output stream
Once an object is created, it will be overwritten if the object exists.
Boolean mkdir (): creates a level-1 folder.
Boolean mkdirs (): Creates a multi-level folder.

Call a method createNewFile () for this class, but in actual operations, you need to pay attention to some things, such as determining whether the file exists and how to write data to the new file.

The Code is as follows: Copy code

Import java. io .*;
Public class CreateNewFile {
// Create a method to create a file. The first parameter of the file is the file path and file name, and the second parameter is the file content.
// For example, myfile.doc HelloJava!
Public void createNewFile (String fileDirectoryAndName, String fileContent ){
Try {
String fileName = fileDirectoryAndName;
// Create a File object. The parameter is of the String type, indicating the directory name.
File myFile = new File (fileName );
// Determine whether the file exists. If not, call the createNewFile () method to create a new directory. Otherwise, the exception handling code is skipped.
If (! MyFile. exists ())
MyFile. createNewFile ();
Else // throw an exception if it does not exist
Throw new Exception ("The new file already exists! ");
// Write the data to the created file below. First, create a file named parameter to create a FileWriter object.
FileWriter resultFile = new FileWriter (myFile );
// Wrap the object into the PrinterWriter object
PrintWriter myNewFile = new PrintWriter (resultFile );
// Use the println () method of the PrinterWriter object to write string data to the new file.
MyNewFile. println (fileContent );
ResultFile. close (); // close the file write stream
} Catch (Exception ex ){
System. out. println ("a new file cannot be created! ");
Ex. printStackTrace ();
}
}
Public static void main (String [] args ){
// Create a Class Object and call the createNewFile () method of the object to create a new file and write data
CreateNewFile createFile = new CreateNewFile ();
CreateFile. createNewFile (args [0], args [1]);
}
}

Run the program. After the code is executed, enter two parameters. The first parameter is the file name. Specify the file type. The Word document is created here. The second parameter is the file content, this parameter is a string of data.


2. Delete
Boolean delete (): returns false if deletion fails. If the file is in use, false is returned if the file cannot be deleted.
Void deleteOnExit (): deletes a file when the program exits.
3. Judgment
Boolean exists (): determines whether a file exists.
IsFile ();
IsDirectory ();
IsHidden ();
IsAbsolute ();
4. Get information
GetName ();
GetPahth (); // obtain the path
GetAbsoluteFile (); // obtain the absolute path and encapsulate it into a file object.
GetAbsolutPath (); // get the absolute path
GetParent ();
LastModified ();
Length ();

GetParent (); // This method returns the parent directory in the absolute path. If the relative path is obtained, null is returned.
// If a level-1 directory exists in the relative path, the directory returns the result.
Renameto ()

The Code is as follows: Copy code

Package com. day1_wd;

Import java. io. File;
Import java. io. IOException;

Public class IODemo {

/**
* @ Param args
* @ Throws IOException
*/
Public static void main (String [] args) throws IOException {
// TODO Auto-generated method stub

}
Private static void method_04 (){
File f = new File ("abc \ test. java ");
Sop (f. getAbsolutePath ());
Sop (f. getParent (); // This method returns the parent directory in the absolute path. If the relative path is obtained, null is returned.
// If there is a previous directory in the relative path, this directory returns the result.
Sop (f. getAbsoluteFile ());
File f2 = new File ("c: \ test. java ");
Sop ("rename" + f. renameTo (f2 ));
}
Private static void method_03 (){
File f = new File ("G: \ sdd \ sssf \ ssf ");
Sop ("isabsolute" + f. isAbsolute ());
Sop (f. getAbsolutePath ());
Sop (f. mkdir ());
Sop (f. exists ());
}
Private static void method_02 () throws IOException {
File f = new File ("a.txt ");
F. deleteOnExit (); // exit the program and delete the file.
If (f. exists () // determines whether the object exists.
F. delete (); // delete
Sop (f. getAbsoluteFile (); // absolute path
Sop (f. createNewFile (); // creates a file and returns a boolean value, such as true. If yes, false is returned.
Sop (f. createNewFile ());
}
Public static void method _ 01 (){
// Encapsulate a.txt as a File object. You can encapsulate existing and existing files or folders into objects.
File f = new File ("a.txt ");
Sop (f. getAbsoluteFile ());
File f1 = new File ("d: \ abc", "a.txt ");
Sop (f1.getAbsoluteFile ());
File f2 = new File ("d: \ abc ");
File f3 = new File (f2, "a.txt ");
Sop (f3 );
// Separator directory delimiter, which can be used across platforms
}
Public static void sop (Object e ){
System. out. println (e );
}

}

Related File Operations

In java, the File class is the only class that can directly operate files:

1. Create a file

The Code is as follows: Copy code

FileDemo01.java:


Import java. io. File;

Import java. io. IOException;

Public class FileDemo01

{

Public static void main (String args [])

{

File f = new File ("e:" + File. separator + "abc.txt"); // declare the object of the File class

Try

{

F. createNewFile (); // create a file based on the specified path

}

Catch (IOException e) // capture and print out exceptions

{

E. printStackTrace ();

}

}

}

 

 

2. delete an object:

The Code is as follows: Copy code

FileDemo02.java


Import java. io. File;

Public class FileDemo02

{

Public static void main (String args [])

{

File f = new File ("e:" + File. separator + "abc.txt ");

F. delete (); // delete an object

}

}

 

 

3. delete a file if it exists. Create a file if it does not exist.

The Code is as follows: Copy code

FileDemo03.java:


Import java. io. File;

Import java. io. IOException;

Public class FileDemo03

{

Public static void main (String args [])

{

File f = new File ("e:" + File. separator + "abc.txt ");

/*

If the file exists, the file is deleted. If the file does not exist, the file is created.

*/

If (f. exists ())

{

F. delete (); // delete an object

}

Else

{

Try

{

F. createNewFile (); // create a file

}

Catch (IOException e)

{

E. printStackTrace ();

}

}

}

}

4. Create a folder

The Code is as follows: Copy code

FileDemo04.java:


Import java. io. File;

Public class FileDemo04

{

Public static void main (String args [])

{

File f = new File ("e:" + File. separator + "nwpu ");

F. mkdir ();

}

}

 

 

5. List Files (only file names are listed)

The Code is as follows: Copy code

FileDemo05.java:


Import java. io. File;

Public class FileDemo05

{

Public static void main (String args [])

{

File f = new File ("e:" + File. separator); // instantiate the object of the File class

String str [] = f. list (); // list objects and return a str Array

For (int I = 0; I <str. length; I ++) // loop output file to see what the output is.

{

System. out. println (str [I]);

}

}

}

 


6. The listFiles () method can be used to list file paths)

The Code is as follows: Copy code

FileDemo06.java:


Import java. io. File;

Public class FileDemo06

{

Public static void main (String args [])

{

File f = new File ("e:" + File. separator); // instantiate the object of the File class

File files [] = f. listFiles (); // List objects

For (int I = 0; I <files. length; I ++)

{

System. out. println (files [I]); // call the toString method to print the output and check the output information.

}

}

}

 


7. Determine whether the directory is: (isDirectory () method)

The Code is as follows: Copy code

FileDemo07.java:


Import java. io. File;

Public class FileDemo07

{

Public static void main (String args [])

{

File f = new File ("e:" + File. separator); // instantiate the object of the File class

If (f. isDirectory ())

{

System. out. println (f. getPath () + "is the directory! ");

}

Else

{

System. out. println (f. getPath () + "not a directory! ");

}

}

}

 


8. list the contents in a given directory (if there is a subdirectory, the contents in the subdirectory are listed)

The Code is as follows: Copy code

FileDemo08.java:

 

Import java. io. File;

Public class FileDemo08

{

Public static void main (String args [])

{

File f = new File ("e:" + File. separator); // instantiate the object of the File class

PrintFile (f );

}

Public static void printFile (File f)

{

If (f! = Null) // determines whether the file is empty.

{

If (f. isDirectory () // determine whether the file is a folder

{

File files [] = f. listFiles (); // List objects

If (files! = Null)

{// Determine whether the directory can be listed

For (int I = 0; I <files. length; I ++)

{

PrintFile (files [I]); // recursive call to determine whether it is a subfolders

}

}

}

Else

{

System. out. println (f );

}

}

}

}

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.