4. Some File Methods To see if inFile is associated to a real file correctly. To see if inFile is associated to a file or not. If false, it is a directory. List the name of all files in the directory C:avaProjectsh12 if ( inFile.exists ( ) ) { if ( inFile.isFile () ) { File directory = new File ( "C:/JavaPrograms/Ch12" ) ; String filename [] = directory.list () ; for ( int i = 0; i < filename.length; i++ ) { System.out.println ( filename [ i ]) ; }
5.
6. Getting Info from JFileChooser int status = chooser.showOpenDialog ( null ) ; if ( status == JFileChooser.APPROVE_OPTION ) { JOptionPane.showMessageDialog ( null , "Open is clicked" ) ; } else { //== JFileChooser.CANCEL_OPTION JOptionPane.showMessageDialog ( null , "Cancel is clicked" ) ; } File selectedFile = chooser.getSelectedFile () ; File currentDirectory = chooser.getCurrentDirectory () ;
7.
8.
9.
10. Sample: Low-Level File Output //set up file and stream File outFile = new File ( "sample1.data" ) ; FileOutputStream outStream = new FileOutputStream ( outFile ) ; //data to save byte [] byteArray = { 10, 20, 30, 40, 50, 60, 70, 80 } ; //write data to the stream outStream.write ( byteArray ) ; //output done, so close the stream outStream.close () ;
11. Sample: Low-Level File Input //set up file and stream File inFile = new File ( "sample1.data" ) ; FileInputStream inStream = new FileInputStream ( inFile ) ; //set up an array to read data in int fileSize = ( int ) inFile.length () ; byte [] byteArray = new byte [ fileSize ] ; //read data in and display them inStream.read ( byteArray ) ; for ( int i = 0; i < fileSize; i++ ) { System.out.println ( byteArray [ i ]) ; } //input done, so close the stream inStream.close () ;
12.
13.
14. Sample Output import java.io.*; class Ch12TestDataOutputStream { public static void main ( String [] args ) throws IOException { . . . //set up outDataStream //write values of primitive data types to the stream outDataStream.writeInt ( 987654321 ) ; outDataStream.writeLong ( 11111111L ) ; outDataStream.writeFloat ( 22222222F ) ; outDataStream.writeDouble ( 3333333D ) ; outDataStream.writeChar ( 'A' ) ; outDataStream.writeBoolean ( true ) ; //output done, so close the stream outDataStream.close () ; } }
15.
16. Sample Input import java.io.*; class Ch12TestDataInputStream { public static void main ( String [] args ) throws IOException { . . . //set up inDataStream //read values back from the stream and display them System.out.println ( inDataStream.readInt ()) ; System.out.println ( inDataStream.readLong ()) ; System.out.println ( inDataStream.readFloat ()) ; System.out.println ( inDataStream.readDouble ()) ; System.out.println ( inDataStream.readChar ()) ; System.out.println ( inDataStream.readBoolean ()) ; //input done, so close the stream inDataStream.close () ; } }
17.
18.
19. Sample Textfile Output import java.io.*; class Ch12TestPrintWriter { public static void main ( String [] args ) throws IOException { //set up file and stream File outFile = new File ( "sample3.data" ) ; FileOutputStream outFileStream = new FileOutputStream ( outFile ) ; PrintWriter outStream = new PrintWriter ( outFileStream ) ; //write values of primitive data types to the stream outStream.println ( 987654321 ) ; outStream.println ( "Hello, world." ) ; outStream.println ( true ) ; //output done, so close the stream outStream.close () ; } }
20. Sample Textfile Input import java.io.*; class Ch12TestBufferedReader { public static void main ( String [] args ) throws IOException { //set up file and stream File inFile = new File ( "sample3.data" ) ; FileReader fileReader = new FileReader ( inFile ) ; BufferedReader bufReader = new BufferedReader ( fileReader ) ; String str; str = bufReader.readLine () ; int i = Integer.parseInt ( str ) ; //similar process for other data types bufReader.close () ; } }
21. Sample Textfile Input with Scanner import java.io.*; class Ch12TestScanner { public static void main ( String [] args ) throws IOException { //open the Scanner Scanner scanner = new Scanner ( new File ( "sample3.data" )) ; //get integer int i = scanner.nextInt () ; //similar process for other data types scanner.close () ; } }
22.
23. Saving Objects Could save objects from the different classes. File outFile = new File ( "objects.data" ) ; FileOutputStream outFileStream = new FileOutputStream ( outFile ) ; ObjectOutputStream outObjectStream = new ObjectOutputStream ( outFileStream ) ; Person person = new Person ( "Mr. Espresso" , 20, 'M' ) ; outObjectStream.writeObject ( person ) ; account1 = new Account () ; bank1 = new Bank () ; outObjectStream.writeObject ( account1 ) ; outObjectStream.writeObject ( bank1 ) ;
24. Reading Objects Must read in the correct order. Must type cast to the correct object type. File inFile = new File ( "objects.data" ) ; FileInputStream inFileStream = new FileInputStream ( inFile ) ; ObjectInputStream inObjectStream = new ObjectInputStream ( inFileStream ) ; Person person = ( Person ) inObjectStream.readObject ( ) ; Account account1 = ( Account ) inObjectStream.readObject ( ) ; Bank bank1 = ( Bank ) inObjectStream.readObject ( ) ;
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
Notas do Editor
When a program that manipulates a large amount of data practical, we must save the data to a file. If we don’t, then the user must reenter the same data every time he or she runs the program because any data used by the program will be erased from the main memory at program termination. If the data were saved, then the program can read them back from the file and rebuild the information so the user can work on the data without reentering them. In this chapter you will learn how to save data to and read data from a file. We call the action of saving data to a file file output and the action of reading data from a file file input . Note: The statements new File( “C:\SamplePrograms”, “one.txt”); and new File(“C:\SamplePrograms\one.text”); will open the same file.
We can start the listing from a current directory by writing String current = System.getProperty ( &quot;user.dir&quot; ) ; JFileChooser chooser = new JFileChooser ( current ) ; or equivalently String current = System.getProperty ( &quot;user.dir&quot; ) ; JFileChooser chooser = new JFileChooser ( ) ; chooser.setCurrentDirectory ( new File ( current )) ;
The accept method returns true if the parameter file is a file to be included in the list. The getDescription method returns a text that will be displayed as one of the entries for the “Files of Type:” drop-down list.
Data is saved in blocks of bytes to reduce the time it takes to save all of our data. The operation of saving data as a block is called data caching . To carry out data caching, part of memory is reserved as a data buffer or cache , which is used as a temporary holding place. Data are first written to a buffer. When the buffer becomes full, the data in the buffer are actually written to a file. If there are any remaining data in the buffer and the file is not closed, those data will be lost.
class TestFileOutputStream { public static void main (String[] args) throws IOException { //set up file and stream File outFile = new File(&quot;sample1.data&quot;); FileOutputStream outStream = new FileOutputStream(outFile); //data to output byte[] byteArray = {10, 20, 30, 40, 50, 60, 70, 80}; //write data to the stream outStream.write(byteArray); //output done, so close the stream outStream.close(); } } The main method throws an exception. Exception handling is described in Section 11.4.
import javabook.*; import java.io.*; class TestFileInputStream { public static void main (String[] args) throws IOException { MainWindow mainWindow = new MainWindow(); OutputBox outputBox = new OutputBox(mainWindow); mainWindow.setVisible( true ); outputBox.setVisible( true ); //set up file and stream File inFile = new File(&quot;sample1.data&quot;); FileInputStream inStream = new FileInputStream(inFile); //set up an array to read data in int fileSize = (int)inFile.length(); byte[] byteArray = new byte[fileSize]; //read data in and display them inStream.read(byteArray); for (int i = 0; i < fileSize; i++) { outputBox.printLine(byteArray[i]); } //input done, so close the stream inStream.close(); } }
You can even mix objects and primitive data type values. For example, outObjectStream.writeInt ( 15 ); outObjectStream.writeObject( account1 ); outObjectStream.writeChar ( 'X' );
You can even mix objects and primitive data type values. For example, outObjectStream.writeInt ( 15 ); outObjectStream.writeObject( account1 ); outObjectStream.writeChar ( 'X' );
class FindSum { private int sum; private boolean success; public int getSum() { return sum; } public boolean isSuccess() { return success; } void computeSum (String fileName ) { success = true; try { File inFile = new File(fileName); FileInputStream inFileStream = new FileInputStream(inFile); DataInputStream inDataStream = new DataInputStream(inFileStream); //read three integers int i = inDataStream.readInt(); int j = inDataStream.readInt(); int k = inDataStream.readInt(); sum = i + j + k; inDataStream.close(); } catch (IOException e) { success = false; } } }
Please use your Java IDE to view the source files and run the program.
Here's the pseudocode to locate a person with the designated name. Notice that for this routine to work correctly, the array must be packed with the real pointers in the first half and null pointers in the last half.