Data stored in variables and arrays is temporary It s lost when a local variable goes out of scope or when the program terminates For long-term retention of data, computers use files. Computers store files on secondary storage devices hard disks, optical disks, flash drives and magnetic tapes. Data maintained in files is persistent data because it exists beyond the duration of program execution.
Java views each file as a sequential stream of bytes (Fig. 8.1). Every operating system provides a mechanism to determine the end of a file, such as an end-of-file marker or a count of the total bytes in the file that is recorded in a system-maintained administrative data structure. A Java program simply receives an indication from the operating system when it reaches the end of the stream
Fig. 8.1 Java s view of a file of n bytes.
File streams can be used to input and output data as bytes or characters. Streams that input and output bytes are known as bytebased streams, representing data in its binary format. Streams that input and output characters are known as character-based streams, representing data as a sequence of characters. Files that are created using byte-based streams are referred to as binary files. Files created using character-based streams are referred to as text files. Text files can be read by text editors. Binary files are read by programs that understand the specific content of the file and the ordering of that content.
A Java program opens a file by creating an object and associating a stream of bytes or characters with it. Can also associate streams with different devices. Java creates three stream objects when a program begins executing System.in (the standard input stream object) normally inputs bytes from the keyboard System.out (the standard output stream object) normally outputs character data to the screen System.err (the standard error stream object) normally outputs character-based error messages to the screen. Class System provides methods setin, setout and seterr to redirect the standard input, output and error streams, respectively.
Java programs perform file processing by using classes from package java.io. Includes definitions for stream classes FileInputStream (for byte-based input from a file) FileOutputStream (for byte-based output to a file) FileReader (for character-based input from a file) FileWriter (for character-based output to a file) You open a file by creating an object of one these stream classes. The object s constructor opens the file.
Can perform input and output of objects or variables of primitive data types without having to worry about the details of converting such values to byte format. To perform such input and output, objects of classes ObjectInputStream and ObjectOutputStream can be used together with the byte-based file stream classes FileInputStream and FileOutputStream.
Class File provides information about files and directories. Character-based input and output can be performed with classes Scanner and Formatter. Class Scanner is used extensively to input data from the keyboard. This class can also read data from a file. Class Formatter enables formatted data to be output to any text-based stream in a manner similar to method System.out.printf.
Class File provides four constructors. The one with a String argument specifies the name of a file or directory to associate with the File object. The name can contain path information as well as a file or directory name. A file or directory s path specifies its location on disk. An absolute path contains all the directories, starting with the root directory, that lead to a specific file or directory. A relative path normally starts from the directory in which the application began executing and is therefore relative to the current directory.
8.3 Class File (cont.) Figure 8.2 lists some common File methods. Fig. 8.2 File methods.
Fig. 8.2 File methods.
import import import import java.io.file; java.io.ioexception; java.util.date; java.util.scanner; /** * * File class used to Obtain file and directory information. */ public class FileDemonstration { public static void main( String[] args) throws IOException { Scanner input = new Scanner (System.in); System.out.print("Enter file or directory name: "); analyzepath(input.nextline()); Fig. 8.3 File class used to obtain file and directory information.
public static void analyzepath (String path) { // create File object based on user input. File name = new File( path ); if ( name.exists()) { System.out.println( name.getname()+" exists"); if (name.isfile()) { System.out.println("is a file"); System.out.printf("%s\n",name.isAbsolute()? "is absolute path":"is not absolute path"); Date dt = new Date(name.lastModified()); // milliseconds to date and time. System.out.println("Last modified at: " + dt); System.out.println("Length: "+name.length()); // in bytes System.out.println("Path: "+name.getpath()); System.out.println("Absolute path: "+name.getabsolutepath()); System.out.println("Parent: "+name.getparent()); System.out.printf("%s%s\n", name,name.delete()?" is deleted": "is not deleted"); if (name.isdirectory()) { System.out.println("is a directory"); System.out.println("\nDirectory contents:"); String[] list = name.list(); for (int i=0; i<list.length; i++) System.out.println(list[i]); else System.out.printf("%s %s\n", path, "does not exist."); // end class
Enter file or directory name: E:\hikmat\research\report.docx report.docx exists is a file output is absolute path Last modified at: Sat Aug 31 13:36:31 EEST 2013 Length: 174562 Path: E:\hikmat\research\report.docx Absolute path: E:\hikmat\research\report.docx Parent: E:\hikmat\research E:\hikmat\research\report.docx is deleted ---------------------------------------------------------------------------------------------------------------------------------------------------------Enter file or directory name: C:\users\public public exists another is a directory Directory contents: Book Place Desktop Documents Downloads Favorites Libraries Music Pictures Recorded TV TEMP Videos output
Sequential-access files store records in order by the record-key field. Text files are human-readable files.
Java imposes no structure on a file Notions such as records do not exist as part of the Java language. You must structure files to meet the requirements of your applications.
// Account class to keep record of one client. import java.io.serializable; class Account implements Serializable { private int number; private String firstname, lastname; private double balance; public Account() { this(0, "", "", 0.0); public Account(int acct, String first, String last, double bal) { setnumber(acct); setfirstname(first); setlastname(last); setbalance(bal); public void setnumber(int num) { number = num; public int getnumber() { return number; public void setfirstname(string first) { firstname = first; public String getfirstname() { return firstname; public void setlastname(string last) { lastname = last; public String getlastname() { return lastname; public void setbalance(double bal) { balance = bal; public double getbalance() { return balance; Fig. 8.4 Account class maintains information for one account.
Formatter outputs formatted Strings to the specified stream. The constructor with one String argument receives the name of the file, including its path. If a path is not specified, the JVM assumes that the file is in the directory from which the program was executed. If the file does not exist, it will be created. If an existing file is opened, its contents are truncated. Solution: use FileWriter with Formatter, example: FileWriter filewriter = new FileWriter ("D:\\userprofile.txt", true); Formatter formatter = new Formatter (filewriter);
// Creating a sequential text file "clients.txt" using formatter. import java.io.filenotfoundexception; import java.util.formatter; import java.util.scanner; public class CreateTextFile { private Formatter output; // object used to output text to file. public void openfile() throws FileNotFoundException output = new Formatter("e:\\clients.txt"); public void addrecords() { Account record = new Account(); Scanner input = new Scanner(System.in); { System.out.println("To terminate, press a non-numeric character"); System.out.print("Enter account number, first name, last name, balance: \n? "); while(input.hasnextint() { record.setnumber(input.nextint()); record.setfirstname(input.next()); record.setlastname(input.next()); record.setbalance(input.nextdouble()); output.format("%-8d %-10s %-10s %-10.2f\r\n", record.getnumber(), record.getfirstname(), record.getlastname(), record.getbalance()); System.out.print("Enter account number, first name, last name, balance: \n? "); public void closefile() { output.close(); Fig. 8.5 Writing data to a sequential text file with class formatter.
class CreateTextFileTest { public static void main(string[] args) throws FileNotFoundException { CreateTextFile application = new CreateTextFile(); application.openfile(); application.addrecords(); application.closefile(); Fig. 8.6 Testing the CreateTextFile class. To terminate, press a non-numeric Enter account number, first name,? 101 Mohammad Jaber 7340.71 Enter account number, first name,? 103 Ahmad Ali 5090.5 Enter account number, first name,? 104 Yousef Saleh 12761 Enter account number, first name,? z 101 103 104 Mohammad Ahmad Yousef Jaber Ali Saleh character last name, balance: output last name, balance: last name, balance: last name, balance: 7340.71 5090.50 12761.00 clients.txt Sample data
The application in Figs. 8.7 and 8.8 reads records from the file "clients.txt" created by the application of Section 8.4.1 and displays the record contents.
import java.io.file; import java.io.filenotfoundexception; import java.util.scanner; // Reading a sequential text file "clients.txt" using Scanner. public class ReadTextFile { private Scanner input; public void openfile() throws FileNotFoundException { input = new Scanner (new File("e:\\clients.txt")); public void readrecords() { System.out.printf("%-10s\t%-10s\t%-10s\t%-10s\r\n", "Account","First Name","Last Name","Balance"); System.out.printf("%-10s\t%-10s\t%-10s\t%-10s\r\n", "-------","----------","---------","-------"); while (input.hasnext()) { System.out.printf("%-10d\t%-10s\t%-10s\t%-10.2f\r\n", input.nextint(), input.next(), input.next(), input.nextdouble()); public void closefile() { input.close(); Fig. 8.7 Sequential file reading using Scanner.
class ReadTextFileTest { public static void main(string[] args) throws FileNotFoundException { ReadTextFile application = new ReadTextFile(); application.openfile(); application.readrecords(); application.closefile(); Account ------101 103 104 Fig. 8.8 First Name ---------Mohammad Ahmad Yousef Testing the ReadTextFile class. Last Name --------Jaber Ali Saleh Balance ------7340.71 5090.50 12761.00 output
To retrieve data sequentially from a file, programs start from the beginning of the file and read all the data consecutively until the desired information is found. It might be necessary to process the file sequentially several times (from the beginning of the file) during the execution of a program. Class Scanner does not allow repositioning to the beginning of the file. The program must close the file and reopen it. Homework Write a program to inquire from the file "clients.txt about the zero balances, credit balances, and debit balances.
The data in many sequential files cannot be modified without the risk of destroying other data in the file. If the name Ali needed to be changed to Mohammad the old name cannot simply be overwritten, because the new name requires more space. Fields in a text file and hence records can vary in size. Records in a sequential-access file are not usually updated in place. Instead, the entire file is usually rewritten. Rewriting the entire file is uneconomical to update just one record, but reasonable if a substantial number of records need to be updated.