The File classes
The File class manipulates disk files and is used to construct FileInputStreams and
FileOutputStreams. Some constructors for the File I/O classes take as a parameter an
object of the File type. When we construct a File object, it represents that file on disk.
When we call its methods, we manipulate the underlying disk file.
The methods for File objects are:
* Constructors
* Test methods
* Action methods
* List methods
Constructors
Constructors allow Java code to specify the initial values of an object. So when you're using
constructors, initialization becomes part of the object creation step. Constructors for the
File class are:
* File(String filename)
* File(String pathname, String filename)
* File(File directory, String filename)
Test Methods
Public methods in the File class perform tests on the specified file. For example:
* The exists() method asks if the file actually exists.
* The canRead() method asks if the file is readable.
* The canWrite() method asks if the file can be written to.
* The isFile() method asks if it is a file (as opposed to a directory).
* The isDirectory() method asks if it is a directory.
These methods are all of the boolean type, so they return a true or false.
Presented by developerWorks, your source for great tutorials ibm.com/developerWorks
Action methods
Public instance methods in the File class perform actions on the specified file. Let's take a
look at them:
* The renameTo() method renames a file or directory.
* The delete() method deletes a file or directory.
* The mkdir() method creates a directory specified by a File object.
* The mkdirs() method creates all the directories and necessary parents in a File
specification.
The return type of all these methods is boolean to indicate whether the action was
successful.
List methods
The list() method returns the names of all entries in a directory that are not rejected by an
optional FilenameFilter. The list() method returns null if the File is a normal file, or
returns the names in the directory. The list() method can take a FilenameFilter filter
and return names in a directory satisfying the filter.
FilenameFilter interface
The FilenameFilter interface is used to filter filenames. You simply create a class that
implements the FilenameFilter. There are no standard FilenameFilter classes
implemented by the Java language, but objects that implement this interface are used by the
FileDialog class and the list() method in the File class.
The implemented accept() method determines if the filename in a directory should be
included in a file list. It is passed the directory and a file name. The method returns true if the
name should be included in the list.
File class: Example code
This example shows a file being tested for existence and a listing of the C:\Windows
directory. The listing is performed for all files and then for files matching a filter.
Here is the example code:
import java.io.*;
import java.util.*;
class FileClassExample
{
public static void main(String argv[])
{
File a_file = new File("test.txt");
if (a_file.canRead())
System.out.println("Can read file");
Presented by developerWorks, your source for great tutorials ibm.com/developerWorks
if (a_file.isFile())
System.out.println("Is a file");
File a_directory = new File("C:backslash, backslashWindows");
// red font indicates that an actual backslash n (carriage return character)
// should be inserted in the code.
if (a_directory.isDirectory())
{
System.out.println("Is a directory");
String names[] = a_directory.list();
for (int i = 0; i < names.length; i++)
{
System.out.println("Filename is " + names[i]);
}
}
System.out.println("Parent is " + a_directory.getParent());
if (a_directory.isDirectory())
{
String names[] = a_directory.list(new MyFilter());
for (int i = 0; i < names.length; i++)
{
System.out.println("Filename is " + names[i]);
}
}
}
}
class MyFilter implements FilenameFilter
{
public boolean accept(File directory, String name)
{
if (name.charAt(0) = = 'A' || name.charAt(0) = = 'a')
return true;
}
}
FileInputStream and FileOutputStream
You can open a file for input or output.
FileInputStream reads from a disk file. You can pass that constructor either the name of
a file or a File object that represents the file. The FileInputStream object is a source of
data.
FileOutputStream writes to a disk file. You can pass it a File object or a name. The
FileOutputStream object is a sink for data.
For FileInputStream and FileOutputStream, you read and write bytes of data.
File: Example code
This example works like the previous examples, except the output is to a file. We open the
file and write the data as bytes. After closing the file, we open it for reading, read all the bytes
in the file, and print them as a string.
Here is the example code:
import java.io.*;
Presented by developerWorks, your source for great tutorials ibm.com/developerWorks
import java.util.*;
class FileExample
{
static BufferedReader system_in = new BufferedReader
(new InputStreamReader(System.in));
public static void main(String argv[])
{
// Create it
{
try
{
FileOutputStream fos = new FileOutputStream("file.dat");
// Read in three hotels
for (int i = 0; i < 3; i++)
{
Hotel a_hotel = new Hotel();
a_hotel.input(system_in);
a_hotel.write_to_fos(fos);
}
fos.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
// Now display it
{
byte [] buffer = null;
File a_file = new File("file.dat");
System.out.println("Length is " + a_file.length());
System.out.println(" Can read " + a_file.canRead());
try
{
FileInputStream fis = new FileInputStream(a_file);
int length = (int) a_file.length();
buffer = new byte[length];
fis.read(buffer);
fis.close();
}
catch(IOException e)
{
System.out.println(e);
}
String s = new String(buffer);
System.out.println("Buffer is " + s);
}
}
}
class Hotel
{
private String name;
private int rooms;
private String location;
boolean input(BufferedReader in)
{
try
{
System.out.println("Name: ");
name = in.readLine();
System.out.println("Rooms: ");
String temp = in.readLine();
rooms = to_int(temp);
System.out.println("Location: ");
location = in.readLine();
}
catch(IOException e)
{
System.err.println(e);
Presented by developerWorks, your source for great tutorials ibm.com/developerWorks
Introduction to Java I/O Page 22
return false;
}
return true;
}
boolean write_to_fos(FileOutputStream fos)
{
try
{
fos.write(name.getBytes());
Integer i = new Integer(rooms);
fos.write(i.toString().getBytes());
fos.write(location.getBytes());
fos.write(' ');
}
catch (IOException e)
{
System.err.println(e);
return false;
}
return true;
}
void debug_print()
{
System.out.println("Name :" + name +
": Rooms : " + rooms + ": at :" + location+ ":");
}
static int to_int(String value)
{
int i = 0;
try
{
i = Integer.parseInt(value);
}
catch(NumberFormatException e)
{}
return i;
}
}
FileReader and FileWriter
FileReader is a convenience subclass of InputStreamReader. FileReader is useful
when you want to read characters from a file. The constructors of FileReader assume a
default character encoding and buffer size. FileReader constructors use the functionality of
InputStreamReader to convert bytes using the local encoding to the Unicode characters
used by Java code.
If you want to read Unicode characters from a file that uses encoding other than the default,
you must construct your own InputStreamReader on FileInputStream.
FileWriter is a convenience subclass of OutputStreamWriter for writing character
files. Constructors for FileWriter also assume default encoding and buffer size. If you
want to use encoding other than the default, you must create your own
OutputStreamWriter on FileOutputStream.
Pages
Langganan:
Posting Komentar (Atom)
0 komentar:
Posting Komentar