Java applications can read data from external resources, including files. Java's File class models an abstract file, including its name and location. In conjunction with other Java classes, developers can create programs in which they can read, write and process file data. An abstract path name forms a key element in the File class, specifying the path to a particular file.
Video of the Day
The File class allows developers to specify the details of a particular file, including its location. Application programming code can use the File class constructor method to create an object instance of the class. The following sample code demonstrates: File dataFile = new File("my_data.txt");
The code passes a text string parameter representing a file. This code example store the file stored in the default application directory, saving it as "my_data.txt" for plain text content. When the Java program processes this line, it resolves the passed parameter into an abstract path name. Alternatively, the constructor method can take two parameters representing parent and child elements of the pathname, as follows: File dataFile = new File("/data", "my_data.txt");
This represents the file stored at the following location: data/my_data.txt
The text file is stored inside a folder named "data," located in the default application directory.
Because it allows code to access external resources, Java's File class forms a major element in many Java applications. Some of these applications use databases; some use data stored in files that can hold formatted data, such as XML markup code. Although the File class models a file location, programs that read from or write to a file must use additional classes. For example, BufferedReader and InputStream provide methods for reading individual data items, such as bytes, from specific file locations.
Using the File class, the abstract path name in Java applications consists of two parts: a prefix and a sequence of names. The prefix, which may be optional, provides the means to cope with the differing ways in which operating systems model and represent directories. The prefix part of a pathname may include a representation of a particular disk drive or a series of one or more slashes indicating directories.
The name elements in an abstract path name consist of text strings that can represent files or folders. In the following example, the string "data" represents the directory and the string "my_data" -- together with the file extension ".txt" -- represents the file. File dataFile = new File("my_data.txt");
Slashes represent the relationships between directories and files. The fact that Java evaluates abstract path names from passed code parameters means that programs can function in multiple operating systems and environments.