Java provides File class in ‘java.io’ package for handling
all basic and necessary file operations and methods used for file handling like
reading the contents of a file, writing to a file, searching for a file,
determining the path of the file stored on a disk, etc. File class contains
number of methods for performing specific operations on a file, few of which
are used in this article.
In this program, the user is checking for the existence of a
particular file stored on system’s hard disk. File class of Java IO package has
been used to provide access to methods like exists(), getName() which checks
for the file and if found returns the message else gives user defined message.
import java.io.File; //file class for basic file operations
class FileHandlingTrial{
public
static void main(String[] args) {
File
asp = new File("C:\\file\\info.txt"); // constructor takes the path
of the file already existing on the system
if(asp.exists()) // built in
method to test whether a specified file exists or not.
System.out.println(asp.getName()
+ "File Found"); // prints the message along with file name
else
System.out.println("File
Not Found");
}
}
In the previous program we checked for an already created
file on the system. We can also create a file using the program with help of
facilities provided by java.io package
import java.util.*;
class FileHandlingTrial{
public
static void main(String[] args) {
final
Formatter asp; //formatter print strings to file
try{
asp
= new Formatter("c://file//trial.txt"); //provide path of file where
it will be stored
System.out.println("File
Created");
}
catch(Exception
e){
System.out.println("Error");
// for possible mistyping of wrong or illegal folder location like specifying a
drive which does not exist on system.
}
}
}
In the next article which will be part 2 of file handling, reading from a file and writing to a
file will be discussed. Thanks folks for reading.
Screenshot // click to open a higher resolution version
0 comments:
Post a Comment