Download presentation
Presentation is loading. Please wait.
Published byJeffrey Black Modified over 9 years ago
1
Files and console applications Chapter 17 This chapter explains: What a file is How to read and write to files How to manipulate folder paths and file names How to write console applications
2
You have already used an editor to create Java source files And an operating system to view a hierarchical structure of directories (folders) Now you will write programs to manipulate files
3
Differences RAM versus file storage devices RAM faster, temporary, store programs as they execute CD-ROMDVDhard drive floppy 650MB4.7GB+-100GB 1.44MB File access: stream or random Java has over 20 classes for file access – each with its own particular set of methods
4
Stream and Random access File a sequence of items processes one after another Random: we can skip to a particular byte position immediately (used for data bases)
5
The essentials of streams 1. open the file 2. read or input data from/into variables 3. close the file Reading from a file (in stream) we can only read the next item. To get to the last we must read all preceding items. Each line ends with an EOLN. (end of line) character. The file ends with an EOF (end of file character)
6
Java I/O classes (input and Output) Reader: BufferedReader, InputStreamReader, Filereader Writer: PrintWriter, FileWriter –Must use import java.io.*; // to use above – “buffer” = large chunks of data
7
BufferedReader and PrintWriter classes readLine method of BufferedReader Reads a whole line of text into a String (StringTokenizer can split that String into parts) printWriter class: print and println (lower case L) both write a String to a file. Println writes an EOLN character at the end after the String The concatenation operator + may be used to join the strings
8
File output: basic elements A text field to accept file name A scrollable text area to accept text (allow copy, cut, paste) A save button to initiate transfer text from text area to file (screenshot page 317 – FileOutputDemo) Program 317-318
9
private PrintWriter outFile inFile = new BufferedReader ( new BufferedReader (nameField.getText ( ) ) ; … while (( line = inFile.readLine ( ) ) ! = null) { … } inFile.close ( ) ;
10
line = inFile.readLine ( ) ; while ( line ! = null) { input TextArea.append ( line + “ \”); line = inFile.readLine( ); } inFile.close ( ); // when the user clicks the ‘open’ button Inputs a file name from the text field. Opens a file with this name and inputs lines from file, appends to text area. If EOF not reached Close the file
11
File Searching J. Doe,53,67 D. Bell,97,99 K. Bush,54,32 etc … (note comma separators) boolean found = false; while ( ( morelines ) && ( ! found) { get firstField; if ( firstField matches name) {found = true; put rest of fields into test fields; }} Screenshot page 324
12
File Search pages 324 - 326 Listing of program The File class Need: import java.io.*;// needs I/O Windows: path C:\temp\java\demo.txt Unix/Linux separator = “/” FileClassDemo program has single ‘Start’ button. Event handling code page 327 … if( event.getSource ( ) = = startButton) { …
13
File class methods page 328 getAbsolutePath – find path getName – extract name getParent – find parent name exists – does file exist isDirectory – is name a directory length – file size in bytes list – fill array with list of file names
14
The JFileChooser class Similar function to word processors, dialog which allows browsing through folders of files Main features program: FileChooserDemo pages 329-331 The file chooser does not actually transfer any data into files the programmer must code that. It provides the program with details about the file the user selects
15
Main features of FileChooser Create instance of JFileChooser class Displays the file chooser by – showOpenDialog or showSaveDialog –// returns a numeric code (has user cancelled dialog or not) –JFIleChooser.APPROVE_OPTION – get SelectedFile method returns instance of File class (we use getAbsolutePath to obtain path)
16
JFileChooser can be used to ‘save’ or open fileChooser = new JFileChooser ( ); reply = fileChooser.showSaveDialog (this) if (reply = = JFileChooser.APPROVE_OPTION) { selectedFile = fileChooser.getSelectedFile( ); nameField.setText ( selectedFile.setAbsolutePath ( ));
17
Console I / O History of user interface –Command line: on screen – scrolled up, next prompt appeared –Menus – users could move cursor –Pointing device (mouse for example) Java can use all of the above Unix and GNU/Linux based on command line software
18
The System class System.out System.in System.err public class ConsoleDemo { public static void main (String [ ] args) { –System.out.println (“Hello World”); }} –// complete program
19
System.in stream private BufferedReader keyBoard ; – keyBoard = new BufferedReader ( new InputStreamReader (System.in) ) ; … –String line = keyBoard.readLine ( ); –… String reply = prompt (“type in your name”); –… System.out.flush –// assure any text sent with print displays immediately
20
system.err Can be used with print and println …System.err.println (“Error … Program Terminating “); … System.exit; // leave program Cause of error given by nemeric code Zero (0) is OK Non-zero = something wrong
21
if (age > 0) { System.exit (0); // normal } – else System.err.println ( “Error in program”); –System.exit(3); // error occurred –}
22
JOptionPane Alternative to System I / O Streams import javax.swing.*; public class ConsoleJOptionDemo { public static void main (String [ ] args ) { –JOptionPane.showMessage ( null, “Hello World”); } } –Console example: Finder program pages 335- 336 program uses two console inputs, a file to search and the required substring. Uses System.in and a prompt is given
23
indexOf method used to search returns -1 if not present. Screenshot page 336 of Finder
24
Reading from a remote site program TinyBrowser pages 337-338 Prompts for URL Displays contents of file on screeen Most of the program concerned with exception handling and console I / O code
25
Essential code of TinyBrowser import java.net.*; Create a connection to a URL URL urlAddress = new URL (urlString); urlConnection = urlAddress.openConnection ( ); inStream = new BufferedReader ( new InputStreamReader ( connection.getInputStream ( ) ) );
26
A malformedURLException may be thrown // bad URL not found Command line arguments Segment of code page 339 FindWithArgs // ommitted part same as Finder program. Pass arguments from command line to FinderWithArguments – javac FinderWithArguments “C:\\temp\myFile.txt” “My interests” –Main points: command line arguments same as parameters. ‘args’ = name of array
27
– the parameters follow the program name after javac args[0] args[1] … etc..length can detect number of parameters passed into main “args.length”
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.