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.

Slides:



Advertisements
Similar presentations
1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
Advertisements

The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 9 Strings and Text I/O.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
Files from Ch4. File Input and Output  Reentering data all the time could get tedious for the user.  The data can be saved to a file. Files can be input.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12 File Input and Output.
File input and output. Interactive vs. file I/O All of the programs we have seen or written thus far have assumed interaction with a user, who types in.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12 File Input and Output.
Java Programming, 3e Concepts and Techniques Chapter 3 Manipulating Data Using Methods.
Files and Streams CS 21a Chapter 11 of Horstmann.
COMP 14 Introduction to Programming Miguel A. Otaduy May 17, 2004.
Chapter 8: Exceptions and I/O Streams Copyright 2002, Matthew Evett. These slides are based on slides copyrighted by John Lewis and William Loftus, 2002,
COMP 14 Introduction to Programming Mr. Joshua Stough February 2, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 29, 2005.
File I/O in Java CS 311, Winter File Basics Recall that a file is block structured. What does this mean? What happens when an application opens.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs1 Programming in Java Objects, Classes, Program Constructs.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
CS 225 Java Review. Java Applications A java application consists of one or more classes –Each class is in a separate file –Use the main class to start.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
Io package as Java’s basic I/O system continue’d.
Streams and File I/O Chapter 14. I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Java Programming, 2E Introductory Concepts and Techniques Chapter 3 Manipulating Data Using Methods.
Files and Streams 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.) –it acts as.
1 Chapter 11 – Files and Streams 1 Introduction What are files? –Long-term storage of large amounts of data –Persistent data exists after termination of.
Very Brief Introduction to Java I/O with Buffered Reader and Buffered Writer.
Console Input. So far… All the inputs for our programs have been hard-coded in the main method or inputted using the dialog boxes of BlueJ It’s time to.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
1 Streams Files are a computer’s long term memory Need ability for programs to –get information from files –copy information from program variables to.
SE-1020 Dr. Mark L. Hornick 1 File Input and Output.
Winter 2006CISC121 - Prof. McLeod1 Last Time Misc. useful classes in Java: –String –StringTokenizer –Math –System.
I/O in Java Dennis Burford
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
JAVA PROGRAMMING BASICS CHAPTER 2. History of Java Begin with project Green in 1991 founded by Patrick Noughton, Mike Sheridan and James Gosling who worked.
By Rachel Thompson and Michael Deck.  Java.io- a package for input and output  File I/O  Reads data into and out of the console  Writes and reads.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 25 – Ticket Information Application Introducing.
Two Ways to Store Data in a File  Text format  Binary format.
Input and Output Using Text Files and Exception Handling.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
 Pearson Education, Inc. All rights reserved Files and Streams.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
 Learn about computer files  Use the Path class  Learn about  Streams  Buffers  file organization  Use Java’s IO classes to write to and read from.
Java Input and Output. Java Input  Input is any information needed by your program to complete its execution  So far we have been using InputBox for.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
java.io supports console and file I/O
CHAPTER 3 File Output.
IO in java.
OO Design and Programming II I/O: Reading and Writing
CMSC 202 Text File I/O.
Java Programming Lecture 2
Streams and File I/O.
Program Input/Output (I/O)
Section 64 – Manipulating Data Using Methods – Java Swing
Objects, Classes, Program Constructs
I/O Basics.
Chapter 12 File Input and Output
Reading and Writing Text Files
File Input and Output.
Chapter 15 Files, Streams and Object Serialization
Presentation transcript:

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

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

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

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)

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)

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

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

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

private PrintWriter outFile inFile = new BufferedReader ( new BufferedReader (nameField.getText ( ) ) ; … while (( line = inFile.readLine ( ) ) ! = null) { … } inFile.close ( ) ;

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

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

File Search pages 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) { …

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

The JFileChooser class Similar function to word processors, dialog which allows browsing through folders of files Main features program: FileChooserDemo pages 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

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)

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 ( ));

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

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

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

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

if (age > 0) { System.exit (0); // normal } – else System.err.println ( “Error in program”); –System.exit(3); // error occurred –}

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 program uses two console inputs, a file to search and the required substring. Uses System.in and a prompt is given

indexOf method used to search returns -1 if not present. Screenshot page 336 of Finder

Reading from a remote site program TinyBrowser pages Prompts for URL Displays contents of file on screeen Most of the program concerned with exception handling and console I / O code

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 ( ) ) );

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

– the parameters follow the program name after javac args[0] args[1] … etc..length can detect number of parameters passed into main “args.length”