File
In this chapter you will learn:
File class
File
deals directly with files and the file system.
File
class describes the properties of a file or a directory itself.
A File
object tells the information associated with a disk file, such
as the permissions, time, date, and directory path, and to navigate subdirectory hierarchies.
A directory in Java is treated simply as a File
with one additional property.
A list of filenames that can be examined by the list()
method.
Create File objects
File(String directoryPath)
directoryPath
is the path name of the fileFile(String directoryPath, String filename)
filename
is the name of the file or subdirectory,File(File dirObj, String filename)
dirObj
is a File object that specifies a directoryFile(URI uriObj)
uriObj
is a URI object that describes a file.
The following table lists different ways to construct a File
object.
File Object | Description |
---|---|
File f1 = new File("/"); | f1 is constructed with a directory path as the only argument. |
File f2 = new File("/","autoexec.bat"); | f2 has the path and the filename. |
File f3 = new File(f1,"autoexec.bat"); | f3 refers to the same file as f2. |
If you use a forward slash (/
) on a Windows, the path will still resolve correctly.
To use a backslash character (\
), you will need
to use its escape sequence (\\
) within a string.
The following code create a File object and output its string representation.
import java.io.File;
//from j av a 2s. c o m
public class Main {
public static void main(String[] args) {
File file = new File("c:/aFolder/aFile.txt");
System.out.println(file);
}
}
The output:
We can also combine a folder and a file to create a File
object.
import java.io.File;
/*from jav a2 s . co m*/
public class Main {
public static void main(String[] args) {
File parent = new File("c:/aFolder");
File aFile = new File(parent, "aFile.txt");
System.out.println(aFile);//c:\aFolder\aFile.txt
}
}
The code above generates the following result.
More examples
Next chapter...
What you will learn in the next chapter: