Work with files in Java. Class File. Basic working methods
This topic describes the basic methods of the File class, which is part of the Java I/O system. For the methods considered, examples are given with explanations.
Contents
- 1. Creating an instance of the File class. Class constructors
- 2. Method getName(). Get file or directory name
- 3. Method getPath(). Get the file name
- 4. Method isAbsolute(). Determine if full path to file is specified
- 5. Method getAbsolutePath(). Get the full path to the file
- 6. Methods canRead(), canWrite(). The determination of whether a file object allows read and write
- 7. Method exists(). Determining the presence of a file (directory)
- 8. Method isDirectory(). Determine if a file object is associated with a directory
- 9. Method isFile(). Determine if a file object is associated with a file
- 10. Method isHidden(). Determine if a file object is hidden
- 11. Method length(). Determine the size in bytes of the file that is associated with the file object
- 12. Method delete(). Deleting a file
- 13. Method mkdir(). Creating a directory
- 14. Method mkdirs(). Create multiple subfolders
- 15. Method renameTo(). Rename the file
- 16. Method getTotalSpace(). Determining disk capacity
- 17. Method getFreeSpace(). Determine free disk space
- 18. Method getUsableSpace(). Determining useful disk space
- Related topics
Search other websites:
1. Creating an instance of the File class. Class constructors
The File class implements several constructors, each of which allows you to create a file or directory name in different ways.
The most common is a constructor that receives a string of type String. This line sets the full (absolute) or abbreviated (relative) name of the file or directory that is being considered (created, defined, etc.).
There are also constructors that form a file name from multiple parts.
Example.
import java.io.*; ... public static void main(String[] args) throws IOException { // Constructors of File class // 1. A constructor that receives a single string of type String, // creates a file object (variable) with the name f1 File f1 = new File("output.txt"); // shortened path is specified String path1 = f1.getPath(); System.out.println(path1); // 2. A constructor that receives two lines: // - the first line sets the absolute path to the file element, // - the second line sets the name of the file element. File f2 = new File("C:\\", "Program Files"); String path2 = f2.getPath(); // path2 = "C:\\Program Files" System.out.println("path2 = " + path2); // 3. Constructor of type File(File, String) File f3 = new File("C:\\Programs\\Java\\Project22"); File f4 = new File(f3,"output.txt"); String path3 = f3.getPath(); String path4 = f4.getPath(); System.out.println("path3 = " + path3); // path3 = C:\Programs\Java\Project22 System.out.println("path4 = " + path4); // path4 = C:\Programs\Java\Project22\output.txt }
The result of the program
output.txt path2 = C:\Program Files path3 = C:\Programs\Java\Project22 path4 = C:\Programs\Java\Project22\output.txt
⇑
2. Method getName(). Get file or directory name
The getName() method returns the name of the file or directory with which the file variable is associated. If the absolute path to the file (directory) name contains several levels of attachment, then the name of this file (directory) is returned directly. The general form of using the method is as follows
name = fileObj.getName();
here
- name – a variable of type String, which is the result of the method;
- fileObj – A file object associated with a file or directory.
Example.
import java.io.*; ... public static void main(String[] args) throws IOException { // Method getName() - get the name of file // Declare a file object and associate it with a file name f = new File("C:\\Program Files"); String name = f.getName(); // name = "Program Files" System.out.println("name = " + name); }
The result of the program
name = Program Files
⇑
3. Method getPath(). Get the file name
The getPath() method returns the name of the file (directory) that was specified in the constructor when creating the file object of type File. The general form of using the method is as follows
path = fileObj.getPath();
here
- path – a string of type String, which is the name of the file (directory) that was set when the file variable fileObj was created.
Example.
import java.io.*; ... public static void main(String[] args) throws IOException { // Method getPath() - get the full path to the file // Declare a file object and associate it with a file name File f = new File("output.txt"); // the name of text file String Path = f.getPath(); System.out.println("Path = " + Path); // Specify the full name when creating the file object f = new File("C:\\Program Files"); Path = f.getPath(); System.out.println("Path = " + Path); // Path = C:\Program Files }
⇑
4. Method isAbsolute(). Determine if full path to file is specified
The isAbsolute() method allows you to determine whether the full path to a file is specified when creating a file object in the constructor of the File class. The general form of using the method is as follows
res = fileObj.isAbsolute();
here
- res – a result that is true if the absolute path was specified when creating the file variable fileObj.
Example.
import java.io.*; ... public static void main(String[] args) throws IOException { // Method IsAbsolute() - is the full path to the file (directory) set // Declare a file object and associate it with a file name File f1 = new File("output.txt"); // shortened path specified boolean res1; res1 = f1.isAbsolute(); System.out.println("res1 = " + res1); // res1 = false // Set full name when creating a file object File f2 = new File("C:\\Program Files"); boolean res2 = f2.isAbsolute(); System.out.println("res2 = " + res2); // res2 = true }
⇑
5. Method getAbsolutePath(). Get the full path to the file
The getAbsolutePath() method returns the full path to the file. The general form of using the method is as follows
path = fileObj.getAbsolutePath();
here
- path – a string of type String, which is the result;
- fileObj – the file object that is associated with the file for which you want to determine the absolute path.
Example.
import java.io.*; ... public static void main(String[] args) throws IOException { // Method GetAbsolutePath() - get the full path to the file // Declare a file object and associate it with a file name File f = new File("output.txt"); // the name of text file String absPath = f.getAbsolutePath(); System.out.println("Path = " + absPath); }
The result of the program
Path = C:\Programs\Java\Project22\output.txt
⇑
6. Methods canRead(), canWrite(). The determination of whether a file object allows read and write
The canRead() and canWrite() methods are used to determine whether a file object can be read or written. If the result is positive, the methods return true.
Example.
import java.io.*; ... public static void main(String[] args) throws IOException { File f = new File("output.txt"); if (f.canRead()) System.out.println("The result of canRead() is true."); else System.out.println("The result of canRead() is false"); if (f.canWrite()) System.out.println("The result of canWrite() is true."); else System.out.println("The result of canWrite() is false"); }
The result of the program
The result of canRead() is true. The result of canWrite() is true.
⇑
7. Method exists(). Determining the presence of a file (directory)
The exists() method is designed to determine the existence of a file associated with a file object. The general form of using the method is as follows
res = fileObj.exists();
here
- res – method’s result. If res = true, then the specified file exists;
- fileObj – The object that is being checked.
Example.
import java.io.*; ... public static void main(String[] args) throws IOException { // Method exists() - determine if a file (directory) exists // Declare a file object and associate it with a file name File f = new File("output.txt"); // the name of text file // If the file f exists, then output the corresponding message if (f.exists()) System.out.println("File is present."); else System.out.println("File is not present"); // Determine if a directory exists File f2 = new File("C:\\Program Files"); if (f2.exists()) System.out.println("The directory is present."); else System.out.println("The directory is not present."); }
⇑
8. Method isDirectory(). Determine if a file object is associated with a directory
The isDirectory() method is designed to determine if a file is a directory (folder). The general form of using the method is as follows
res = fileObj.isDirectory();
here
- res – the value of type bool. If res = true, then the file is a directory;
- fileObj – the file object that is being checked.
Example.
import java.io.*; ... public static void main(String[] args) throws IOException { // IsDirectory method - determine if a file is a directory (folder) // 1. Declare a file variable and associate it with a file or folder name File f = new File("C:\\Program Files"); // name of the folder to be checked // If the file f exists, then determine its type if (f.exists()) { if (f.isDirectory()) { System.out.println("Directory."); } else System.out.println("File."); } else System.out.println("The file is not present"); }
⇑
9. Method isFile(). Determine if a file object is associated with a file
The isFile() method returns true if the file object is associated with the file. The general form of using the method is as follows
res = fileObj.isFile();
here
- res – calculation result. If the file object is a file, then res = true;
- fileObj – file object.
Example.
import java.io.*; ... public static void main(String[] args) throws IOException { // Method isFile() - determine if a file object is associated with a file // 1. Declare a file object and associate it with a file name File f = new File("output.txt"); // If the file f exists, then determine its type if (f.exists()) { if (f.isFile()) { System.out.println("File object is file."); } else System.out.println("File object is not file."); } else System.out.println("The file is not present"); }
⇑
10. Method isHidden(). Determine if a file object is hidden
The isHidden() method returns true if the file object is associated with a file that has the hidden attribute set. General form of using the method
res = fileObj.isHidden();
here
- fileObj – file object;
- res – the result of the method. If res = true, then the file object is associated with the hidden file.
Example.
import java.io.*; ... public static void main(String[] args) throws IOException { File f = new File("output.txt"); if (f.isHidden()) System.out.println("The file \"output.txt\" is hidden."); else System.out.println("The file \"output.txt\" is not hidden."); }
⇑
11. Method length(). Determine the size in bytes of the file that is associated with the file object
The length() method is used to determine the file size and has the following general form
long length()
Example.
import java.io.*; ... public static void main(String[] args) throws IOException { // Determine file size in bytes // 1. Declare a file variable File f = new File("abc.txt"); // 2. Create a stream that writes characters to the file f FileWriter fw = new FileWriter(f); // 3. Write the string "Hello world!" to the file fw.write("Hello world!"); // 4. Close stream fw.close(); // 5. Determine the length of the file "abc.txt" long len = f.length(); // 6. Print file length to console System.out.println("len = " + len); // len = 12 }
The result of the program
len = 12
⇑
12. Method delete(). Deleting a file
The delete() method is used to delete a file. General form of using the method
res = fileObj.delete();
here
- fileObj – the file object that is associated with the file to be deleted.
- res – the result of the method. If res = true, then the file deletion was successful.
Example.
import java.io.*; ... public static void main(String[] args) throws IOException { // Method delete() - delete file by it's name // Declare file variable File f = new File("somefile.txt"); // Delete file if it exists if (f.exists()) { f.delete(); System.out.println("The file is deleted."); } else System.out.println("The file is not present."); }
⇑
13. Method mkdir(). Creating a directory
The mkdir() method is used to create a folder (directory). The general form of using the method is as follows
res = fileObj.mkdir();
here
- res – the result of type bool. If the directory was created successfully, then res = true, otherwise res = false;
- fileObj – an object of type File, which is associated with the name of the directory being created.
Example. A directory is created with the name 123 in the current directory.
import java.io.*; ... public static void main(String[] args) throws IOException { // Method mkdir() - create a directory // 1. Declare a file variable and associate it with a folder // in the current directory (sets the relative path). File f = new File("123"); // If the directory does not exist, then create it if (!f.exists()) { if (f.mkdir()) { System.out.println("The folder is created!"); } else System.out.println("The folder is not created."); } else System.out.println("The folder is present."); // 2. Create a file variable and associate it with a folder // C:\Programs\345 - absolute path to the folder. File f2 = new File("C:\\Programs\\345"); boolean res = f2.mkdir(); if (res) System.out.println("The folder C:\\Programs\\345 is created."); else System.out.println("The folder C:\\Programs\\345 is not created."); }
The result of the program
The folder is present. The folder C:\Programs\345 is created.
⇑
14. Method mkdirs(). Create multiple subfolders
The mkdirs() method allows you to create multiple levels of folder attachments at a time. Unlike the mkdir() method, this method creates nesting levels of folders that do not exist. In the mkdir() method, to create a subfolder, you must first have a top-level folder created.
The general form of using the method is as follows:
res = fileObj.mkdirs();
here
- fileObj – a file object that contains a string with the name or names of folders to be created.
- res – the result of the method. If the folder sequence was created successfully, then res = true.
Example.
import java.io.*; ... public static void main(String[] args) throws IOException { // Create folders at the specified path File f = new File("C:\\ABC\\DEF\\GHI"); // Create folders C:\ABC, C:\ABC\DEF, C:\ABC\DEF\GHI if (f.mkdirs()) System.out.println("The folders is created."); else System.out.println("The folders is not created"); }
⇑
15. Method renameTo(File). Rename the file
The renameTo() method is designed to rename a file. The general form of using the method is as follows
res = f1.renameTo(f2);
here
- res – the result of the method. If the file is renamed successfully, then res = true, otherwise res = false;
- f1 – the file variable corresponding to the source file to be renamed;
- f2 – a file variable corresponding to the new name of the source file f1 after renaming it.
Example.
import java.io.*; ... public static void main(String[] args) throws IOException { // renameTo() - rename the file. // Rename strings.txt to array.txt. // Both files specify a relative path // 1. Declare a file variable and associate it with a file File f1 = new File("abc.txt"); File f2 = new File("array.txt"); // If file f1 exists, rename it if (f1.exists()) { if (f1.renameTo(f2)) { System.out.println("Ok!"); } else System.out.println("The file is not renamed."); } else System.out.println("The file is not present"); }
⇑
16. Method getTotalSpace(). Determining disk capacity
Using the getTotalSpace() method, you can determine the total size of the disk in bytes. The method returns a result of type long. The general form of using the method is as follows
totalSpace = fileObj.getTotalSpace();
here
- fileObj – file object in which the name of the disk is determined for which the size is determined;
- totalSpace – a variable of type long, which is the result of the method.
Example.
import java.io.*; ... public static void main(String[] args) throws IOException { // Determine disk size File f = new File("E:\\"); // Determine the total volume of the hard disk E: long totalSpace = f.getTotalSpace(); System.out.println("Drive E: - Total space = " + totalSpace); // Determine the size of drive C: f = new File("C:\\"); totalSpace = f.getTotalSpace(); System.out.println("Drive C: - Total space = " + totalSpace); }
The result of the program
Drive E: - Total space = 790486839296 Drive C: - Total space = 208684355584
⇑
17. Method getFreeSpace(). Determine free disk space
Using the getFreeSpace() method, you can determine the amount in bytes of free space on the disk. The general form of using the method is as follows
space = fileObj.getFreeSpace();
here
- fileObj – a file object that contains the media name, file name, or folder name. If a file or folder name is specified, then the amount of free space for the media on which this disk and file are located is determined;
- space – a variable of type long, which is the result of the method.
Example.
import java.io.*; ... public static void main(String[] args) throws IOException { // Determine disk size File f = new File("E:\\"); // Determine the size of free disk space long freeSpace = f.getFreeSpace(); System.out.println("Drive E: - Free space = " + freeSpace); // Determine the available disk space C: f = new File("C:\\"); freeSpace = f.getFreeSpace(); System.out.println("Drive C: - Free space = " + freeSpace); }
The result of the program
Drive E: - Free space = 197617647616 Drive C: - Free space = 18358034432
⇑
18. Method getUsableSpace(). Determining useful disk space
Using the getUsableSpace() method, you can determine the usable size of space on the disk. In many cases, the value that this method returns is equal to the value that getFreeSpace() returns. The general form of using the method is as follows:
space = fileObj.getUsageSpace();
where
- fileObj – a file object that contains a disk name or file name. If a file name is defined for fileObj, then the volume of the medium on which this file is stored is determined;
- space – a variable of type long, which is the size of the usable disk space.
Example.
import java.io.*; ... public static void main(String[] args) throws IOException { // Determine the disk space File f = new File("E:\\"); // Determine the amount of usable space on drive E: long usableSpace = f.getUsableSpace(); System.out.println("Drive E: - Usable space = " + usableSpace); // Determine the size of the C: drive and the free space on the C: drive f = new File("C:\\"); usableSpace = f.getUsableSpace(); System.out.println("Drive C: - Usable space = " + usableSpace); }
The result of the program
Drive E: - Usable space = 197617647616 Drive C: - Usable space = 18358034432
⇑
Related topics
- Java I/O system. Streams. Byte streams. Character streams. Standard streams
- Work with the console. Classes InputStreamReader, PrintStream. Creating an input/output stream associated with the console. Redirecting input/output streams
⇑