Files and I/O


Web interfaces are a trend, but it is not without issues. One of the issues is the data saved in variables will be erased after the current task (e.g., clicking on a button to display the file contents) is done. If you are using the text interfaces, then this issue does not usually happen because the program does not have to be exited when the task is done. However, this may not be considered as a problem since web programs would become more modular as each button normally matches one program. In order to solve this problem, databases or files are usually used with websites to save the data.

The File class from the java.io package allows us to work with files. The File class has many useful methods for creating and getting information about files.
// Import the File class.
import java.io.File;

// Specify the filename.
File myObj = new File( "filename.txt" );

Method Type Description
canRead( ) Boolean Tests whether the file is readable or not.
canWrite( ) Boolean Tests whether the file is writable or not.
createNewFile( ) Boolean Creates an empty file.
delete( ) Boolean Deletes a file.
exists( ) Boolean Tests whether the file exists.
getName( ) String Returns the name of the file.
getAbsolutePath( ) String Returns the absolute pathname of the file.
length( ) Long Returns the size of the file in bytes.
list( ) String[ ] Returns an array of the files in the directory.
mkdir( ) Boolean Creates a directory.




      A bird in the hand is better than two in the bush.