20.1. File Methods
Friday, April 16, 2010
In order to use more methods of File class just go to java.io package in Java API.
File Methods
The File class provides several methods for manipulating files and directories. Here are some of these methods.
Let ’s see how these methods work by trying out the following example:
File Methods
The File class provides several methods for manipulating files and directories. Here are some of these methods.
public String getName() //Returns the filename or the directory name of this File object . public boolean exists() //Tests if a file or a directory exists. public long length() //Returns the size of the file. public long lastModified() //Returns the date in milliseconds when the file was last modified. public boolean canRead() //Returns t rue if it ’s permissible to read from the file. Otherwise, it returns false. public boolean canWrite() //Returns t rue if it ’s permissible to write to the file. Otherwise, it returns false. public boolean isFile() //Tests if this object is a file, that is, our normal percept ion of what a file is (not a directory) . public boolean isDirectory() //Tests if this object is a directory. public String[] list() //Returns the list of files and subdirectories within this object . This object should be a directory. public void mkdir() //Creates a directory denoted by this abst ract pathname. public void delete() //Removes the actual file or directory represented by this File object .
Let ’s see how these methods work by trying out the following example:
package files1; // File Class Methods Demo import java.io.File; /** * * @author Administrator */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here //Input any file at command line String fileName = "C:\\Program Files\\NetBeans 6.1\\LICENSE.txt"; File fn = new File(fileName); System.out.println("Name: " + fn.getName()); if (!fn.exists()) { System.out.println(fileName + " does not exists."); /* Create a temporary directory instead. */ System.out.println("Creating temp directory..."); fileName = "temp"; fn = new File(fileName); fn.mkdir(); System.out.println(fileName +(fn.exists()? "exists": "does not exist")); System.out.println("Deleting temp directory..."); fn.delete(); System.out.println(fileName +(fn.exists()? "exists": "does not exist")); return; } System.out.println(fileName + " is a " +(fn.isFile()? "file." :"directory.")); if (fn.isDirectory()) { String content[] = fn.list(); System.out.println("The content of this directory:"); for (int i = 0; i < content.length; i++) { System.out.println(content[i]); } } if (!fn.canRead()) { System.out.println(fileName + " is not readable."); return; } System.out.println(fileName + " is " + fn.length() +" bytes long."); System.out.println(fileName + " is " + fn.lastModified()+ " bytes long."); if (!fn.canWrite()) { System.out.println(fileName + " is not writable."); } } }When we compile this program we can get the fallowing output Name: LICENSE.txt C:\Program Files\NetBeans 6.1\LICENSE.txt is a file. C:\Program Files\NetBeans 6.1\LICENSE.txt is 77141 bytes long. C:\Program Files\NetBeans 6.1\LICENSE.txt is 1212117964000 bytes long. Sequential-Access Text Files In this section, we create and manipulate sequential access files. These files are in which records are stored in order by the record-key filed. Creating Sequential File In order to store data in a file first we need to create a class, let us assume the fallowing class.
// A class that represents one record of Information package seqfiles; /** * * @author Administrator */ public class AccountRecord { private int account; private String firstname; private String lastname; private double balance; public AccountRecord() { this(0,"","",0.0); } public AccountRecord(int acct,String first,String last,double bal) { setAccount(acct); setFirstname(first); setLastname(last); setBalance(bal); } public int getAccount() { return account; } public void setAccount(int account) { this.account = account; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } }After this we need to implement Formatter class to write data into the file.
//Writing data to a text file with class Formatter package seqfiles; import java.util.Formatter; import java.util.Scanner; /** * * @author Administrator */ public class CreateTextFile { private Formatter output; // To open a file public void openFile() { try { output=new Formatter("clients.txt"); } catch(Exception e) { System.out.println("You do not have write access to this file"); System.exit(1); } } // To add records to the file public void addRecords() { AccountRecord record=new AccountRecord(); Scanner input=new Scanner(System.in); System.out.println("To terminate input, typeNow take a Main class and create an object for CreateTextFile and execute the program.then press "); System.out.println("Enter Account Number, First Name, Last Name and Balance"); while(input.hasNext()) { try { record.setAccount(input.nextInt()); record.setFirstname(input.next()); record.setLastname(input.next()); record.setBalance(input.nextDouble()); if(record.getAccount() > 0) { output.format("%d %s %s %.2f", record.getAccount(),record.getFirstname(),record.getLastname(),record.getBalance()); } else { System.out.println("Account Number must greater than 0"); } } catch(Exception e) { System.out.println("Error writing to File"); } } } // To close File public void closeFile() { if(output !=null) { output.close(); } } }
//Execution of the application package seqfiles; /** * * @author Administrator */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here CreateTextFile application=new CreateTextFile(); application.openFile(); application.addRecords(); application.closeFile(); } }Now you can see a text file will be created in your source code directory and which contains the Information of AccountRecord class. Reading Data from a Sequential-Access Text File For this we need to write another program which implements Scanner class of java.util package. Let us see how it works.
//This program reads a text file and display each record package seqfiles; import java.io.File; import java.util.Scanner; /** * * @author Administrator */ public class ReadTextFile { private Scanner input; // To open a file public void openFile() { try { input=new Scanner(new File("clients.txt")); } catch(Exception e) { System.out.println("Error opening File"); } } // To read Record from the file public void readRecord() { AccountRecord record=new AccountRecord(); System.out.printf("%s %s %s %s\n", "Account","First Name","Last Name","Balance"); try { while(input.hasNext()) { record.setAccount(input.nextInt()); record.setFirstname(input.next()); record.setLastname(input.next()); record.setBalance(input.nextDouble()); System.out.printf("%d %s %s %.2f", record.getAccount(),record.getFirstname(),record.getLastname(),record.getBalance()); } } catch(Exception e) { input.close(); } } // To close File public void closeFile() { if(input !=null) { input.close(); } } }In order to implement this, we need to create an object for the above class then the output will contains the record of the file clients.txt.
//Execution of the application package seqfiles; /** * * @author Administrator */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here ReadTextFile application=new ReadTextFile(); application.openFile(); application.readRecord(); application.closeFile(); } }
Labels:
Files and Streams