Java Learning Notes-file operations (API)

Source: Internet
Author: User
Tags throw exception

One: summary of knowledge points

1. The file class is used only for information that represents files (directories) and cannot be accessed on the contents of a file.

2. Path issues when creating a file object

(1) File File=new file ("absolute path");

"Absolute path":

1) Windows:

    1. "D:/test"-------the Automatic Processing method provided by Java, the programmer is more commonly used
    2. "D:\\test"-----escape character
    3. "D:" +file.separator+ "Test"

2) Linnux/unix/mac

A "/home/soft01/test"

B. "/home/soft01/" +file.separator+ "test"

(2) file File=new file ("relative path");

Relative path: No difference between Windows and Linux

such as: "Demo/test"-------for convenience, cross-platform, often use relative path

Relative start position: The start path of the Main method, which is the current project folder in Eclipse

File f=new Flie ("demo");

F.mkdir ()

Tip: Abstract paths should use relative paths as far as possible, and the hierarchy delimiter of the directory should not be written directly "/" or "\", and should be expressed using the File.separator constant to avoid differences between different systems.

3. Construction Method:
(1) File File=new file ("name");

(2) file parent= new file ("demo");

File file= new file (Parent,name);

Two: Code exercise:

1. Create a folder using the file API,

Just create an object in memory, no folder on the hard disk

File File=new file ("E:" +file.separator+ "filetest");

Create folder on hard disk, return value True, create successful (original not)

Instead, the creation fails (there are already folders or files)

Boolean Ok=file.mkdir ();

System.out.println (OK);

Similarly, create a file----Note that an exception is thrown here, and you need to add throws IOException

File F=new file ("E:" +file.separator + "Filetest" +file.separator+ "test.txt");

Boolean ok=f.createnewfile ();

System.out.println (OK);

2. Create a new folder in the current folder demo

"Current Folder" is the folder of the current project! viewing results using Refresh (F5)

"Where the" demo "parameter is a relative path

Create a file in the demo folder

File F=new file ("demo");

F.mkdir ();

File File=new file ("Hello");

File.createnewfile ();

Access the files in the demo folder that the F points to

File A=new file (F, "test.txt");

A.createnewfile ();

Create a subfolder in the Demo folder

File File1=new file (F, "one");

File1.mkdir ();

3. Create a series of paths (multilevel folders) on the hard disk at a time

File File = new file ("Myhome/job/days/day01/am");

File.mkdirs ();

4.//file.exists () to check if there are files on the hard disk, folder

File.isfile () If the file being checked is returned true

File.isdirectory () If the check is that the folder returns True

Boolean found=file.exists ();

SYSTEM.OUT.PRINTLN (found);

Boolean f=file.isfile ();

Boolean d=file.isdirectory ();

System.out.println (f);

System.out.println (d);

5. Access files that already exist to obtain file-related information

File File = new file ("d:/welcome.html");

Length of file: Byte data in a file

Long L = file.length ();

System.out.println (l);

System.out.println (l/1024d);

Last modification of the file modify time----

The output is inside the folder (including the last modified time of the sub-file)

Long time = file.lastmodified ();

SimpleDateFormat format =

New SimpleDateFormat (

"Yyyy-mm-dd HH:mm:ss");

System.out.println (Format.format (time));

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

6. Delete () deletes the hard drive file pointed to by one, cannot delete the folder with content (folder contains sub-files or sub-folders can not)!

File one = new file ("demo", "One");

Boolean OK = One.delete ();

System.out.println (OK);//true

7. Files or folders that begin with a. Start on Linux are hidden

File File2 = new file (". Home");

8. Rename the folder (file) to File2 name, return True to indicate that the modification was successful

9. Rename the folder (file) to the name of the File2,

Returns true to indicate that the modification succeeded,

File File2 = new file ("MyHome");

File File = new file ("Home");

Boolean Success=file.renameto (File2);

SYSTEM.OUT.PRINTLN (Success);

Note: File2 must not be created on the hard drive, output false. and file must be a folder that has already been created

10. Listfiles () is called on file or non-existent file, the underlying IO error is returned null!

11. Call the Listfiles () method on the folder to return the entire contents of the folder (child files, folders)

Contains hidden files! Returns an array of type file, the element is a folder or a file

File Myhome=new file ("MyHome");

File[] Files=myhome.listfiles ();

System.out.println (arrays.tostring (files));

Note: Only the sub-folders below the output myhome\job,job are not output

12.

/**

* Calculates the total length of all files in a directory, retrieving only the total length of files in the current directory, without subfolders

* @param dir directory name

* Total length of @return file

* @throws filenotfoundexception file

* The folder does not exist, or is not an exception when folders are thrown.

*/

public class Ioutils {

public static long Size (String dir)

Throws filenotfoundexception{

/*

* Create a File object

* Check for presence, throw exception!

* Check if it is a folder! Throw an exception!

* Get the full contents of the file (sub-files, subfolders).

* Traverse all content.

* If it is a file (Isfile ())

* The length of the statistics file.

* Return to statistical results

*/

File File = new file (dir);

exists exists

if (! file.exists ()) {

Throwing an exception is the end of the method, is not the correct end!

throw New FileNotFoundException (

"Folder does not exist:" +dir);

}

File already exists, check for files

if (File.isfile ()) {

throw New FileNotFoundException (

"Not folder:" +dir);

}

Get the entire contents of a folder (child files, folders)

file[] files = file.listfiles ();

file[] files = file.listfiles (onlyfile);

The length of the statistic file

Long Count = 0;

for (File f:files) {

F represents sub-files, folders in a folder

if (F.isfile ()) {

Count+=f.length ();

}

Count+=f.isfile ()? F.length (): 0;

}

return count;

}

}

Test

public static void Main (string[] args) throws IOException {

TODO auto-generated Method Stub

File File=new file ("Demo/demo.txt");

File.createnewfile ();

try{

Long S=ioutils.size ("Demo/demo.txt");

System.out.println (s);

System.out.println (s/1024d/1024);

}catch (FileNotFoundException e) {

E.printstacktrace ();

}

}

Note: There is a problem, do not know why?

Exception in thread "main"java.lang.NullPointerException

Long S=ioutils.size ("Demo/demo.txt");

public static void Main (string[] args) {

13. Conditional access to the contents of a folder

Define filters, accept only files

/**

* Determines whether the given parameter file is an acceptable result.

* Returns True if file is required, otherwise false

*/

FileFilter onlyfile = new FileFilter () {

Accept Acceptance

Public boolean accept (file file) {

return File.isfile ();

}

};

After the anonymous inner class ends

File dir = new file ("d:/");

/**

* The Listfiles method will automatically call Onlyfile

* In the Accept method, will satisfy the condition of the file left

* Come as a result, not satisfied with the abandonment.

*/

file[] files = dir.listfiles (onlyfile);

for (File file:files) {

GetName returns the name of the file

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

}

}

Three Question Questions

1. Get the length of bytes in the file, based on what? Why is there a folder output is 0, some of the output of several folders fixed? 's All

File File3=new file ("E:/1.javaprogram");

Long L=file3.length ();

System.out.println (l);

System.out.println (l/1024d);

Output: 4096 4.0

File File3=new file ("E:/1. 0.eclipse ");

Long L=file3.length ();

System.out.println (l);

System.out.println (l/1024d);

Output: 0 0.0

Answer: File.length () If the reading is a folder then the byte is not fixed?????

2. The following code why refresh in the project folder shows deleted files, but the output file is also deleted files, the output is myhome/job/days/day01/am, but the file5.exists () output statement returns false

File File5=new file ("Myhome/job/days/day01/am");

System.out.println (File5.delete ());

System.out.println (FILE5);

System.out.println (File5.exsits ());

3. In the current directory to create three files, if the two filenames are spelled the same (when the case is different), why the refresh is not established later, but the output indicates that the folder has been established, output: Three true?????

File File=new file ("demo");

File.mkdir ();

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

File File1=new file ("Demo");

File1.mkdir ();

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

File File2=new file ("Mo");

File2.mkdir ();

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

Java Learning Notes-file operations (API)

Related Article

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.