Chapter 11. Directory and Filesystem Operations

Introduction

This chapter is largely devoted to one class: java.io.File. The File class gives you the ability to list directories, obtain file status, rename and delete files on disk, create directories, and perform other filesystem operations. Many of these would be considered “system programming” functions on some operating systems; Java makes them all as portable as possible.

Note that many of the methods of this class attempt to modify the permanent file store, or disk filesystem, of the computer you run them on. Naturally, you might not have permission to change certain files in certain ways. This can be detected by the Java Virtual Machine’s (or the browser’s, in an applet) SecurityManager, which will throw an instance of the unchecked exception SecurityException. But failure can also be detected by the underlying operating system: if the security manager approves it, but the user running your program lacks permissions on the directory, for example, you will either get back an indication (such as false) or an instance of the checked exception IOException. This must be caught (or declared in the throws clause) in any code that calls any method that tries to change the filesystem.

11.1. Getting File Information

Problem

You need to know all you can about a given file on disk.

Solution

Use a java.io.File object.

Discussion

The File class has a number of “informational” methods. To use any of these, you must construct a File object containing ...

Get Java Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.