26.07.2013 Views

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

932 Files and Streams Chapter 16<br />

25<br />

26 // if user clicked Cancel but<strong>to</strong>n on dialog, return<br />

27 if ( result == JFileChooser.CANCEL_OPTION )<br />

28 return;<br />

29<br />

30 // obtain selected file<br />

31 File fileName = fileChooser.getSelectedFile();<br />

32<br />

33 // display error if file name invalid<br />

34 if ( fileName == null ||<br />

35 fileName.getName().equals( "" ) )<br />

36 JOptionPane.showMessageDialog( null,<br />

37 "Invalid File Name", "Invalid File Name",<br />

38 JOptionPane.ERROR_MESSAGE );<br />

39<br />

40 else {<br />

41<br />

42 // open file<br />

43 try {<br />

44 RandomAccessFile file =<br />

45 new RandomAccessFile( fileName, "rw" );<br />

46<br />

47 RandomAccessAccountRecord blankRecord =<br />

48 new RandomAccessAccountRecord();<br />

49<br />

50 // write 100 blank records<br />

51 for ( int count = 0; count < 100; count++ )<br />

52 blankRecord.write( file );<br />

53<br />

54 // close file<br />

55 file.close();<br />

56<br />

57 // display message that file was created<br />

58 JOptionPane.showMessageDialog( null,<br />

59 "Created file " + fileName, "Status",<br />

60 JOptionPane.INFORMATION_MESSAGE );<br />

61<br />

62 System.exit( 0 ); // terminate program<br />

63 }<br />

64<br />

65 // process exceptions during open, write or<br />

66 // close file operations<br />

67 catch ( IOException ioException ) {<br />

68 JOptionPane.showMessageDialog( null,<br />

69 "Error processing file", "Error processing file",<br />

70 JOptionPane.ERROR_MESSAGE );<br />

71<br />

72 System.exit( 1 );<br />

73 }<br />

74 }<br />

75<br />

76 } // end method openFile<br />

77<br />

Fig. Fig. 16.12 16.12 Creating a random-access file sequentially (part 2 of 3).

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!