Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use File class method in Java

2025-02-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Today, the editor will share with you the relevant knowledge points about how to use the File class method in Java. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article.

Overview of the File class

The File class represents platform-independent files and directories under the java.io package. File can create, delete, and rename files and directories, but cannot access the contents of the files themselves, and if you need to access the contents, you need to access them through the input / output stream.

The File class can create an File instance using a file path string, which can be either absolute or relative. The general relative path is specified by the system property user.dir, that is, the path where the Java VM is located.

File class commonly used constructor / * Creates a new File instance by converting the given * pathname string into an abstract pathname. If the given string is * the empty string, then the result is the empty abstract pathname. * * @ param pathname A pathname string * @ throws NullPointerException * If the pathname argument is null * / public File (String pathname) {if (pathname = = null) {throw new NullPointerException ();} this.path = fs.normalize (pathname); this.prefixLength = fs.prefixLength (this.path);} common methods of File class

Public String getName (): returns the file name or directory name represented by the File object lock (or, in the case of a directory, the last subdirectory).

Public String getParent (): returns the pathname corresponding to this File object and returns the String type.

Public File getParentFile (): returns the parent directory of this File object and returns the File type.

Public String getPath (): returns the pathname corresponding to this File object and returns the String type.

Public boolean isAbsolute (): determines whether the file or directory corresponding to the File object is an absolute path.

Public String getAbsolutePath (): returns the absolute path corresponding to this File object and returns the String type.

Public String getCanonicalPath () throws IOException:

Public File getCanonicalFile () throws IOException:

Public File getAbsoluteFile (): returns the absolute path corresponding to this File object and returns the File type.

Public boolean canRead (): determines whether the file or directory corresponding to this File object is readable.

Public boolean canWrite (): determines whether the file or directory corresponding to this File object is writable.

Public boolean canExecute (): determines whether the file or directory corresponding to this File object is executable.

Public boolean exists (): determines whether the file or directory corresponding to this File object exists.

Public boolean isDirectory (): determines whether this File object is a directory.

Public boolean isFile (): determines whether this File object is a file.

Public boolean isHidden (): determines whether this File object is hidden.

Public long lastModified (): returns the timestamp of the last modification of the File object, which we can display with SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss"); formatted as time and date.

Public boolean setLastModified (long time): sets the timestamp of the last modification of the File object.

Public long length (): returns the file content length of the File object.

Public boolean createNewFile () throws IOException: when the file corresponding to this File object does not exist, this method creates a new file specified by the File object, and returns true; if it is successfully created. Otherwise, it returns false.

Public boolean delete (): delete the file or directory corresponding to the File object. If the deletion is successful, return true;. Otherwise, false is returned.

Public void deleteOnExit (): Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates. It means to delete the file or directory when VM is closed, unlike when the delete () method is called. It is generally appropriate for temporary files.

Public String [] list (): lists all child file names and pathnames of the File object, and returns an array of String.

Public File [] listFiles (): lists all the child files and pathnames of the File object, and returns an array of File.

Public boolean mkdir (): create a directory and can only create a subclass under an existing parent class. If the parent class does not have one, you cannot create a subclass.

Public boolean mkdirs (): also creates a directory, and can create a subfolder if the parent folder does not exist, and recursively create the parent folder, by the way.

Public boolean renameTo (File dest): renames the file or directory corresponding to this File object, and returns true; if renamed successfully. Otherwise, false is returned.

Public boolean setReadOnly (): sets this File object to read-only permissions.

Public boolean setWritable (boolean writable, boolean ownerOnly): write permission setting. If writable is true, write access is allowed; if false, write access is not allowed. If ownerOnly is true, write access applies only to the owner; otherwise, it applies to everyone.

Public boolean setWritable (boolean writable): the underlying implementation is via setWritable (writable, true), which by default applies only to file or directory owners.

Public boolean setWritable (boolean writable) {return setWritable (writable, true);}

Public boolean setReadable (boolean readable, boolean ownerOnly): read permission setting. If readable is true, read access is allowed; if false, read access is not allowed. If ownerOnly is true, read access applies only to the owner; otherwise, it applies to everyone.

Public boolean setReadable (boolean readable): the underlying implementation is via setReadable (readable, true), which by default applies only to file or directory owners.

Public boolean setReadable (boolean readable) {return setReadable (readable, true);}

Public boolean setExecutable (boolean executable, boolean ownerOnly): execute permission settings. If executable is true, access is allowed; if false, access is not allowed. If ownerOnly is true, the execute access applies only to the owner; otherwise it applies to everyone.

Public boolean setExecutable (boolean executable): the underlying implementation is via setExecutable (executable, true), which by default applies only to file or directory owners.

Public boolean setExecutable (boolean executable) {return setExecutable (executable, true);}

Public static File [] listRoots (): lists all the root paths of the system, which can be called directly through the File class.

Public long getTotalSpace (): returns the total space size, in bytes by default.

Public long getFreeSpace (): Returns the number of unallocated bytes in the partition, which returns the amount of unallocated space. The default unit is bytes.

Public long getUsableSpace (): Returns the number of bytes available to this virtual machine on the partition, which returns the amount of free space. The default unit is bytes.

Public Path toPath (): returns the Path object of the File object.

Public static File createTempFile (String prefix, String suffix) throws IOException: create a temporary file in the directory where temporary files are stored by default. It can be called directly using the File class, with a given prefix, a system-generated random number, and a given suffix as the file name. Prefix is at least 3 bytes long. If suffix is set to null, the default suffix is .tmp.

Public static File createTempFile (String prefix, String suffix, File directory): create a temporary file in the specified temporary file directory directort. It can be called directly using the File class, with a given prefix, a system-generated random number, and a given suffix as the file name. Prefix is at least 3 bytes long. If suffix is set to null, the default suffix is .tmp.

Examples of common methods

1) run the main class

Package com.example.andya.demo;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import java.io.File;import java.io.IOException;import java.net.URI;import java.nio.file.Path;import java.text.SimpleDateFormat;@SpringBootApplicationpublic class DemoApplication {public static void main (String [] args) throws IOException {File file = new File ("C:\\ Users\\ LIAOJIANYA\\ Desktop\ filetest\\ filedir02\\ FileTest.txt") System.out.println ("getName ():" + file.getName ()); System.out.println ("getParent ():" + file.getParent ()); System.out.println ("getParentFile ():" + file.getParentFile ()); System.out.println ("getAbsolutePath ():" + file.getAbsolutePath ()); System.out.println ("getAbsoluteFile ():" + file.getAbsoluteFile () System.out.println ("getAbsoluteFile (). GetParent ():" + file.getAbsoluteFile (). GetParent ()); System.out.println ("getPath ():" + file.getPath ()); System.out.println ("isAbsolute ():" + file.isAbsolute ()); System.out.println ("getCanonicalPath ():" + file.getCanonicalPath () System.out.println ("getCanonicalFile ():" + file.getCanonicalFile ()); System.out.println ("canRead ():" + file.canRead ()); System.out.println ("canWrite ():" + file.canWrite ()); System.out.println ("canExecute ():" + file.canExecute ()); System.out.println ("exists ():" + file.exists () System.out.println ("isDirectory ():" + file.isDirectory ()); System.out.println ("isFile ():" + file.isFile ()); System.out.println ("isHidden ():" + file.isHidden ()); System.out.println (file.setLastModified (1546275661)); SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss") System.out.println ("lastModified ():" + simpleDateFormat.format (file.lastModified (); / / write the three numbers System.out.println ("length ():" + file.length ()); File newFile01 = newFile ("C:\\ Users\\ LIAOJIANYA\\ Desktop\ filetest\\ filedir02\\ FileTest1.txt"); newFile01.createNewFile (); newFile01.delete () File newDir1 = new File ("C:\\ Users\\ LIAOJIANYA\ Desktop\\ filetest\\ filedir02\\ dir1"); System.out.println ("mkdir ():" + newDir1.mkdir ()); File newDir2 = new File ("C:\\ Users\\ LIAOJIANYA\\ Desktop\\ filetest\ filedir02\\ dir2\\ dir2-1"); System.out.println ("mkdirs ():" + newDir2.mkdirs ()) String [] fileList = file.getParentFile () .list (); System.out.println ("= all files and paths in the previous directory ="); for (String fileName: fileList) {System.out.println (fileName) } System.out.println ("file rename:" + file.renameTo ("C:\\ Users\\ LIAOJIANYA\\ Desktop\\ filetest\\ filedir02\\ FileTest.txt")); System.out.println ("= all files and directories in the previous directory ="); File [] files = file.getParentFile (). ListFiles () For (File fileName: files) {System.out.println (fileName.getName ());} System.out.println ("canRead ():" + file.canRead ()); / / unwritable System.out.println ("setWritable ():" + file.setWritable (false, false)); System.out.println ("canWrite ():" + file.canWrite ()) System.out.println ("canExecute ():" + file.canExecute ()); System.out.println ("= relative path ="); / / the default relative path is user.dir, that is, System.out.println ("user.dir:" + System.getProperty ("user.dir")); File newFile = newFile ("test.txt") System.out.println ("whether the newFile file exists:" + newFile.exists ()); newFile.createNewFile (); System.out.println ("whether it exists after the new newFile file is created:" + newFile.exists () + ", path is:" + newFile.getAbsolutePath ()); System.out.println ("getName ():" + newFile.getName () System.out.println ("getParent ():" + newFile.getParent ()); System.out.println ("getParentFile ():" + newFile.getParentFile ()); System.out.println ("getAbsolutePath ():" + newFile.getAbsolutePath ()); System.out.println ("getAbsoluteFile ():" + newFile.getAbsoluteFile () System.out.println ("getAbsoluteFile (). GetParent ():" + newFile.getAbsoluteFile (). GetParent ()); System.out.println ("getPath ():" + newFile.getPath ()); System.out.println ("isAbsolute ():" + newFile.isAbsolute ()); System.out.println ("getCanonicalPath ():" + newFile.getCanonicalPath () System.out.println ("getCanonicalFile ():" + newFile.getCanonicalFile ()); URI uri = newFile.toURI (); System.out.println ("URI:" + uri.toString ()); File [] listRoots = File.listRoots (); System.out.println ("= all files and paths under the system root =") For (File root: listRoots) {System.out.println (root);} System.out.println ("getTotalSpace ():" + file.getTotalSpace () / 1024Accord 1024 + "G"); System.out.println ("getFreeSpace ():" + file.getFreeSpace () / 1024Accord 1024 + "G") System.out.println ("getUsableSpace ():" + file.getUsableSpace () / 1024 args 1024 + G "); Path path = file.toPath (); System.out.println (" Path: "+ path); SpringApplication.run (DemoApplication.class, args);}}

2) running result:

GetName (): FileTest.txtgetParent (): C:\ Users\ LIAOJIANYA\ Desktop\ filetest\ filedir02getParentFile (): C:\ Users\ LIAOJIANYA\ Desktop\ filetest\ filedir02getAbsolutePath (): C:\ Users\ LIAOJIANYA\ Desktop\ filetest\ filedir02\ FileTest.txtgetAbsoluteFile (): C:\ Users\ LIAOJIANYA\ Desktop\ filetest\ filedir02\ FileTest.txtgetAbsoluteFile (). GetParent (): C:\ Users\ LIAOJIANYA\ Desktop\ filetest\ filedir02getPath (): C:\ Users\ LIAOJIANYA\ Desktop\ filetest\ filedir02\ FileTest.txtisAbsolute (): FileTest.txtisAbsolute (): C:\ Users\ LIAOJIANYA\ Desktop\ filetest\ filedir02\ FileTest.txtgetCanonicalFile (): C:\ Users\ LIAOJIANYA\ Desktop\ filetest\ filedir02\ FileTest.txtcanRead (): truecanWrite (): falsecanExecute (): trueexists (): trueisDirectory (): falseisFile (): trueisHidden (): falsetruelastModified (): 1970-01-19 05:31:15length (): 3mkdir (): falsemkdirs (): all files and paths under false= 's upper-level directory = dir1dir2FileTest.txtfile rename: all texts under true= 's upper-level directory Parts and directories = dir1dir2FileTest.txtcanRead (): truesetWritable (): truecanWrite (): falsecanExecute (): true= relative path = user.dir:C:\ DATA\ selfcodenewFile file exists: true after the new newFile file exists: true The path is: C:\ DATA\ selfcode\ test.txtgetName (): test.txtgetParent (): nullgetParentFile (): nullgetAbsolutePath (): C:\ DATA\ selfcode\ test.txtgetAbsoluteFile (): C:\ DATA\ selfcode\ test.txtgetAbsoluteFile (). GetParent (): C:\ DATA\ selfcodegetPath (): test.txtisAbsolute (): falsegetCanonicalPath (): C:\ DATA\ selfcode\ test.txtgetCanonicalFile (): C:\ DATA\ selfcode\ test.txtURI:file:/C:/DATA/selfcode/test.txt= system All files and paths in the root directory = C:\ getTotalSpace (): 237 GgetFreeSpace (): 41 GgetUsableSpace (): 41 GPath: C:\ Users\ LIAOJIANYA\ Desktop\ filetest\ filedir02\ FileTest.txt

3) some verification of the results: a) file length and modification time

B) after the setting is not writable:

B) disk size

C) user.dir path

CreateTempFile temporary file creation example

1) run the main class

File file2 = new File ("C:\ Users\ LIAOJIANYA\ Desktop\ filetest\ filedir01"); File tmp01 = file2.createTempFile ("tmp01", ".tmp"); File tmp02 = file2.createTempFile ("tmp02", ".tmp", file2); tmp02.deleteOnExit (); File tmp03 = File.createTempFile ("tmp03", null); System.out.println ("tmp01:" + tmp01.getAbsolutePath ()) System.out.println ("tmp02:" + tmp02.getAbsolutePath ()); System.out.println ("tmp03:" + tmp03.getAbsolutePath ())

2) running result

Tmp01: C:\ Users\ LIAOJI~1\ AppData\ Local\ Temp\ tmp01870328708927314810.tmp

Tmp02: C:\ Users\ LIAOJIANYA\ Desktop\ filetest\ filedir01\ tmp023046960943790159256.tmp

Tmp03: C:\ Users\ LIAOJI~1\ AppData\ Local\ Temp\ tmp032224782289258299121.tmp

3) View the results:

A) default temporary file storage address:

B) specify the temporary file storage address:

Among them, if you need to create a temporary file in the requirement, the temporary file may be used as storage, but if you need to delete the file after the program runs, you can use the deleteOnExit () method.

FilenameFilter file filter exampl

Use of the public String [] list (FilenameFilter filter) method. 1) run the main class

Public class DemoApplication {public static void main (String [] args) {File file = new File ("C:\\ Users\\ LIAOJIANYA\\ Desktop\\ filetest\\ filedir02\"); String [] nameArr = file.list (dir, name)-> name.endsWith (".doc")); for (String name: nameArr) {System.out.println (name);}

2) running result:

File 01.doc

3) verify:

Where, by using Lambda expressions, the target type is FilenameFilter for file filtering, which filters files that end in .doc.

These are all the contents of this article entitled "how to use File methods in Java". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report