SCJP : File
Given a scenario involving navigating file systems, reading from files, or writing to files, develop the correct solution
using the following classes (sometimes in combination), from java.io:
BufferedReader, BufferedWriter, File,
FileReader, FileWriter and PrintWriter.
File
Files and directories are accessed and manipulated via the java.io.File class. The
File class does not actually provide for input and output to files. It simply provides
an identifier of files and directories.
Always remember that just because a File object is created, it does not mean there actually
exists on the disk a file with the identifier held by that File object.
The File class includes several overloaded constructors. For example, the following
instance of File refers to a file named myfile.txt in the current
directory of the program that the JVM is running:
File file = new File ("myfile.txt");
Again, the file myfile.txt may or may not exist in the file system. An attempt
to use File object that refers to a file that does not exist will cause
a FileNotFoundException to be thrown.
The File instance can also created with a filename that includes path:
File fileA = new File("/tmp/filea.txt");
Another overloaded constructor allows separate specification of the path and the file name:
File fileA = new File("/tmp", "filea.txt");
Directories can also be specified:
File directoryA = new File("/tmp");
There are a number of useful methods in File, e.g.:
boolean exist(); // does the file exist
boolean canWrite(); // can the file be written to
boolean canRead(); // can the file be read
boolean isFile(); // does it represent a file
boolean isDirectory(); // or a directory
There are also methods to get the file name and path components, to make a directory, to get a listing of the
files in a directory, etc.
String getName(); // get the name of the file (no path included)
String getPath(); // get the abstract file path
String getCanonicalPath(); // get the name of the file with path
String getAbsolutePath(); // get the absolute file path.
NOTE, the getCanonicalPath() method first converts this pathname to absolute form
if necessary, as if by invoking the getAbsolutePath() method, and then maps
it to its unique form in a system-dependent way. This typically involves removing redundant names
such as "." and ".." from the pathname, resolving symbolic
links (on UNIX platforms), and converting drive letters to a standard case (on Microsoft Windows platforms).
NOTE, that path names use different separator characters on different hosts. Windows
uses "\", Unix - "/", Macintosh - ":".
The static variables:
File.separator // string with file separator
File.separatorChar // char with file separator
File.pathSeparator // string with path separator
File.pathSeparatorChar // char with path separator
can be used to insure that your programs are platform independent. For example, this snippet shows how
to build a platform independent path:
String dirName = "dataDir";
String filename = "data.dat";
File filData = new File(dirName + File.separator + filename);
The File class includes the method:
boolean mkdir();
This method will create a directory with the abstract path name represented by the File object
if that File object represents a directory. The method returns
true if the directory creation succeeds and false if not. A
situation in which the directory cannot be created is, for example, when the
File object refers to an actual file that already exists in the file system.
Instances of the File class are immutable; that is, once created, the abstract
pathname represented by a File object will never change.
This example lists the files and subdirectories in a directory:
File dir = new File("directoryName");
String[] children = dir.list();
if (children == null) {
// Either dir does not exist or is not a directory
} else {
for (int i=0; i<children.length; i++) {
// Get filename of file or directory
String filename = children[i];
}
}
It is also possible to filter the list of returned files. This example does not return any files that start with '.' :
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return !name.startsWith(".");
}
};
children = dir.list(filter);
The list of files can also be retrieved as File objects:
File[] files = dir.listFiles();
This filter only returns directories:
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);
FileReader
Convenience class for reading character files. The constructors of this class assume that the default character
encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an
InputStreamReader on a FileInputStream.
FileReader is meant for reading streams of characters. For reading streams of
raw bytes, consider using a FileInputStream.
Constructors:
public FileReader(String fileName) throws FileNotFoundException
public FileReader(File file) throws FileNotFoundException
public FileReader(FileDescriptor fd)
Some methods:
// Read a single character
public int read() throws IOException
// Read characters into a portion of an array
public int read(char cbuf[], int offset, int length) throws IOException
// Read characters into an array. This method will block until some input
// is available, an I/O error occurs, or the end of the stream is reached.
public int read(char cbuf[]) throws IOException
try {
BufferedReader in = new BufferedReader(new FileReader("inFileName"));
String str;
while ((str = in.readLine()) != null) {
process(str);
}
in.close();
} catch (IOException e) {
}
BufferedReader
Read text from a character-input stream, buffering characters so as to provide for the efficient reading of
characters, arrays, and lines.
The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.
In general, each read request made of a Reader causes a corresponding
read request to be made of the underlying character or byte stream. It is therefore
advisable to wrap a BufferedReader around any Reader whose
read() operations may be costly, such as
FileReaders and InputStreamReaders. For example:
BufferedReader in = new BufferedReader(new FileReader("foo.in"));
will buffer the input from the specified file. Without buffering, each invocation of
read() or readLine() could cause bytes to be read from the
file, converted into characters, and then returned, which can be very inefficient.
Programs that use DataInputStreams for textual input can be localized by
replacing each DataInputStream with an appropriate
BufferedReader.
Constructors:
public BufferedReader(Reader in, int sz)
public BufferedReader(Reader in)
Some methods:
// Read a single character
public int read() throws IOException
// Read characters into a portion of an array
public int read(char cbuf[], int off, int len) throws IOException
// Read a line of text. A line is considered to be terminated by any one
// of a line feed ('\n'), a carriage return ('\r'), or a carriage return
// followed immediately by a linefeed.
//
// ignoreLF - If true, the next '\n' will be skipped
String readLine(boolean ignoreLF) throws IOException
// Read a line of text. A line is considered to be terminated by any one
// of a line feed ('\n'), a carriage return ('\r'), or a carriage return
// followed immediately by a linefeed.
// same as 'readLine(false)'
public String readLine() throws IOException
// Methods to work with marks (positions in the stream)
public void mark(int readAheadLimit) throws IOException
public void reset() throws IOException
public boolean markSupported()
// Example reads from from one file and writes to another.
// Assume inFile and outFile are Strings with path/file names.
try {
BufferedReader bufReader = new BufferedReader(new FileReader(inFile));
BufferedWriter bufWriter = new BufferedWriter(new FileWriter(outFile));
String line = null;
while ((line=bufReader.readLine()) != null){
bufWriter.write(line);
bufWriter.newLine(); // adds newline character(s)
}
bufReader.close();
bufWriter.close();
} catch (IOException e) {
}
FileWriter
Convenience class for writing character files. The constructors of this class assume that the default character
encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an
OutputStreamWriter on a FileOutputStream.
Whether or not a file is available or may be created depends upon the underlying platform. Some platforms,
in particular, allow a file to be opened for writing by only one FileWriter (or
other file-writing object) at a time. In such situations the constructors in this class will fail if the
file involved is already open.
FileWriter is meant for writing streams of characters. For writing streams of
raw bytes, consider using a FileOutputStream.
Constructors:
public FileWriter(String fileName) throws IOException
// if 'append' parameter is 'true', then data will be written
// to the end of the file rather than the beginning
public FileWriter(String fileName, boolean append) throws IOException
public FileWriter(File file) throws IOException
public FileWriter(File file, boolean append) throws IOException
public FileWriter(FileDescriptor fd)
Some methods:
// Write an array of characters
public void write(char[] cbuf) throws IOException
// Write a single character
public void write(int c) throws IOException
// Write a portion of an array of characters
public void write(char cbuf[], int off, int len) throws IOException
// Write a string
public void write(String str) throws IOException
// Write a portion of a string
public void write(String str, int off, int len) throws IOException
Writing to a File. If the file does not already exist, it is automatically created:
try {
BufferedWriter out = new BufferedWriter(new FileWriter("outFileName"));
out.write("aString");
out.close();
} catch (IOException e) {
}
Appending to a File:
try {
BufferedWriter out = new BufferedWriter(new FileWriter("fileName", true));
out.write("aString");
out.close();
} catch (IOException e) {
}
BufferedWriter
Write text to a character-output stream, buffering characters so as to provide for the efficient writing of
single characters, arrays, and strings.
The buffer size may be specified, or the default size may be accepted. The default is large enough for most purposes.
A newLine() method is provided, which uses the platform's own notion of line separator
as defined by the system property line.separator. Not all platforms use the newline
character ('\n') to terminate lines. Calling this method to terminate each output line is therefore preferred to
writing a newline character directly.
In general, a Writer sends its output immediately to the underlying character or byte stream.
Unless prompt output is required, it is advisable to wrap a BufferedWriter around
any Writer whose write() operations may be costly, such as
FileWriters and OutputStreamWriters. For example:
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
will buffer the PrintWriter's output to the file. Without buffering, each invocation
of a print() method would cause characters to be converted into bytes that would then
be written immediately to the file, which can be very inefficient.
Constructors:
public BufferedWriter(Writer out)
public BufferedWriter(Writer out, int sz) // sz - Output-buffer size
Some methods:
// Write a portion of an array of characters
public void write(char cbuf[], int off, int len) throws IOException
// Write a single character
public void write(int c) throws IOException
// Write a portion of a string
public void write(String str, int off, int len) throws IOException
// Write an array of characters (inherited from class java.io.Writer)
public void write(char[] cbuf) throws IOException
// Write a string (inherited from class java.io.Writer)
public void write(String str) throws IOException
// Write a line separator. The line separator string is defined by the system property
// 'line.separator', and is not necessarily a single newline ('\n') character.
public void newLine() throws IOException
// Flush the stream
public void flush() throws IOException
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("aaa.txt"));
bw.write ("Java");
bw.flush ();
bw.close ();
} catch (IOException e) {
}
PrintWriter
Print formatted representations of objects to a text-output stream. This class implements all of the
print methods found in PrintStream. It does not contain methods
for writing raw bytes, for which a program should use unencoded byte streams.
Unlike the PrintStream class, if automatic flushing is enabled it will be done only
when one of the println, printf, or format methods
is invoked, rather than whenever a newline character happens to be output. These methods use the
platform's own notion of line separator rather than the newline character.
Methods in this class never throw I/O exceptions, although some of its constructors may. The client may
inquire as to whether any errors have occurred by invoking checkError().
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class FileOutput {
public static void main(String[] args) {
try {
BufferedWriter out = new BufferedWriter(new FileWriter("test.txt"));
PrintWriter pw = new PrintWriter(out);
int i = 30;
double j = 102.90;
boolean b = true;
pw.print(i);
pw.print(j);
pw.print(b);
pw.close();
out.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
The test.txt file contents:
30102.9true
|