Java Reference
In-Depth Information
Table 6.1
Common File Extensions
Extension
Description
text file
.txt
Java source code file
.java
compiled Java bytecode file
.class
Microsoft Word file
.doc
Microsoft Excel file
.xls
Adobe Portable Document File
.pdf
audio file
.mp3
image file
.jpg
compressed archive
.zip
hypertext markup language files (most often web pages)
.html
executable file
.exe
Files can be classified into text files and binary files depending on the format that
is used. Text files can be edited using simple text editors. Binary files are stored using
an internal format that requires special software to process. Text files are often stored
using the .txt extension, but other file formats are also text formats, including
.java and .html files.
To access a file from inside a Java program, you need to construct an internal
object that will represent the file. The Java class libraries include a class called File
that performs this duty.
You construct a File object by passing in the name of a file, as in the following
line of code:
File f = new File("hamlet.txt");
Once you've constructed the object, you can call a number of methods to manip-
ulate the file. For example, the following program calls a method that determines
whether a file exists, whether it can be read, what its length is (i.e., how many char-
acters are in the file), and what its absolute path is (i.e., where it is stored on the
computer):
1 // Report some basic information about a file.
2
3 import java.io.*; // for File
4
5 public class FileInfo {
6 public static void main(String[] args) {
7 File f = new File("hamlet.txt");
 
Search WWH ::




Custom Search