Files
Unless otherwise restricted, a Java application can read and write to the host filesystem with the same level of access as the user who runs the Java interpreter. Java applets and other kinds of untrusted applications can, of course, be restricted by the security policy and cut off from these services. We’ll discuss applet access at the end of this section. First, let’s take a look at the tools for basic file access.
Working with files in Java is still somewhat problematic. The host filesystem lies outside of Java’s virtual environment, in the real world, and can therefore still suffer from architecture and implementation differences. Java tries to mask some of these differences by providing information to help an application tailor itself to the local environment; we’ll mention these areas as they occur.
The java.io.File Class
The java.io.File
class encapsulates access to information about a file or directory
entry in the filesystem. It can be used to get attribute information
about a file, list the entries in a directory, and perform basic
filesystem operations like removing a file or making a directory.
While the File object handles these tasks, it
doesn’t provide direct access for reading and writing file
data; there are specialized streams for that purpose.
File constructors
You can
create an instance of File from a
String
pathname:
File fooFile = new File( "/tmp/foo.txt" ); File barDir = new File( "/tmp/bar" );
You can also create a file with a relative path:
File f = ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access