Chapter 5 IO Files
Chapter 5 IO Files
if (out != null) {
out.close(); }
}
Buffered Reader and Writer
BufferedReader in= null;
PrintWriter out= null;
try {
in= new BufferedReader(new FileReader("xanadu.txt"));
out = new PrintWriter(new FileWriter("characteroutput.txt"));
String b;
while ((b = in.readLine()) != null) {
out.println(l); } }
finally {
if (in!= null) {
in.close(); }
if (out!= null) {
out m.close(); } }
File (java.io.File)
Most of the classes defined by java.io operate on streams, the
File class does not.
File deals directly with files and the file system. That is, the
File class does not specify how information is retrieved from
or stored in files; it describes the properties of a file itself.
File object is used to obtain or manipulate the information
associated with a disk file, such as the permissions, time, date,
and directory path, and to navigate subdirectory hierarchies.
We should use standard stream input/output classes to direct
access for reading and writing file data
Other Operations on Java Files
Constructor
File(String directoryPath)
File(String directoryPath, String filename)
To Get Paths
getAbsolutePath(), getPath(), getParent(),
getCanonicalPath()
To Check Files
isFile(), isDirectory(), exists()
To Get File Properties
getName(), length(), isAbsolute(), lastModified(), isHidden()
//length in bytes
Cont…..
To Get File Permissions
canRead(), can Write(), canExecute()
To Know Storage information
getFreeSpace(), getUsableSpace(), getTotalSpace()
Utility Functions
Boolean createNewFile()
Boolean renameTo(File nf); renames the file and returns true if
success
Boolean delete(); deletes the file represented by path of file
(also delete directory if its empty)
Boolean setLastModified(long ms) sets timestamp(Jan 1, 1970 UTC as a
start time)
Boolean setReadOnly() to mark file as readable (also can be
done writable, and executable.)