Java Chapter 2 (Estifanos Tilahun Mihret--Tech with Estif)

Slides:



Advertisements
Similar presentations
The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
Advertisements

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.
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.
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.
Chapter 9 Streams and File I/O Overview of Streams and File I/O
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.
Chapter 91 Streams and File I/O Chapter 9. 2 Announcements Project 5 due last night Project 6 assigned Exam 2 –Wed., March 21, 7:00 – 8:00 pm, LILY 1105.
HST 952 Computing for Biomedical Scientists Lecture 8.
1 Text File I/O  I/O streams  Opening a text file for reading  Closing a stream  Reading a text file  Writing and appending to a text file.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
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.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
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.
Streams and File I/O Chapter 9. Objectives become familiar with the concept of an I/O stream understand the difference between binary files and text files.
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 Scientific Programming Chapter 9 – Stream & File I/O.
Files and Streams 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
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.
Input / Output Chapter 13.  We use files all the time  Programs are files  Documents are files  We want them to be “permanent”  To last beyond execution.
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.
Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser.
Lecturer: Dr. AJ Bieszczad Chapter 9 COMP 150: Introduction to Object-Oriented Programming 9-1 l Overview of Streams and File I/O l Text File I/O l Binary.
Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 9 l Streams and Simple File I/O l Exception Handling with File.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
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.
Streams and File I/O Chapter 9. Outline Overview of Streams and File I/O Text-File I/O Using the File Class Basic Binary-File I/O Object I/O with Object.
Chapter 10 Text Files Section 10.2 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
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.
Chapter 9 1 Chapter 9 – Part 2 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.
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.
1 Exceptions Exception handling – Exception Indication of problem during execution – E.g., divide by zero – Chained exceptions Uses of exception handling.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
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.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Announcements/Reminders l Project 6 due on Thursday March 31 (3 weeks)
Java IO Exploring the java.io package and living to talk about it.
CHAPTER 3 File Output.
IO in java.
OO Design and Programming II I/O: Reading and Writing
CMSC 202 Text File I/O.
Streams and File I/O.
Ch14 Files and Streams OBJECTIVES
Streams and File I/O.
University of Central Florida COP 3330 Object Oriented Programming
I/O Streams A stream is a sequence of bytes that flows from a source to a destination In a program, we read information from an input stream and write.
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
CSS161: Fundamentals of Computing
Streams and File I/O Chapter 9 Chapter 9.
Chapter 17 Binary I/O Dr. Clincy - Lecture.
Streams and File I/O Chapter 14.
Chapter 12 File Input and Output
Chapter 17 – Files and Streams
CSS 161: Fundamentals of Computing
MSIS 670: Object-Oriented Software Engineering
File I/O ICS 111: Introduction to Computer Science I
I/O Streams A stream is a sequence of bytes that flow from a source to a destination In a program, we read information from an input stream and write information.
Computer Programming with JAVA
Files and Streams in Java
14 Files and Streams.
Chapter 15 Files, Streams and Object Serialization
Presentation transcript:

Advanced Programming Estifanos T. (MSc in Computer Networking)

CHAPTER TWO Streams and File I/O Estifanos T. (MSc in Computer Networking)

Objectives 3 Lecture 2: Streams and File I/O 9/9/2019 Estifanos T. (MSc in Computer Networking) To explain the concepts of Streams in Java To describe the various stream classes To discuss how to use streams and object streams To explore File Management

Introduction 4 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O Storage of data in variables and arrays is temporary Files used for long-term retention of large amounts of data, even after the programs that created the data terminate Persistent data – exists beyond the duration of program execution Files stored on secondary storage devices Stream – ordered data that is read from or written to a file

Data Hierarchy 5 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O Computers process all data items as combinations of zeros and ones Bit – smallest data item on a computer, can have values 0 or 1 Byte – 8 bits Characters – larger data item Consists of decimal digits, letters and special symbols Character set – set of all characters used to write programs and represent data items Unicode – characters composed of two bytes ASCII – 7/8 bits representation

Data Hierarchy 6 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O Fields – a group of characters or bytes that conveys meaning Record – a group of related fields File – a group of related records Data items processed by computers form a data hierarchy that becomes larger and more complex from bits to files Record key – identifies a record as belonging to a particular person or entity – used for easy retrieval of specific records Sequential file – file in which records are stored in order by the record-key field Database – a group of related files Database Management System – a collection of programs designed to create and manage databases

Data Hierarchy 7 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O

I/O Overview 8 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or a file Output can be to display (screen) or a file Advantages of file I/O Permanent copy Output from one program can be input to another Input can be automated (rather than entered manually)

Streams 9 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O 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 a buffer between the data source and destination Input stream: a stream that provides input to a program System.in is an input stream, implemented via Scanner Class Output stream: a stream that accepts output from a program System.out is an output stream A stream connects a program to an I/O object System.out connects a program to the screen System.in connects a program to the keyboard

Streams 10 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O

Binary vs Text Files 11 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O All data and programs are ultimately just zeros and ones Each digit can have one of two values, hence binary Bit is one binary digit Byte is a group of eight bits Text files: the bits represent printable characters One byte per character for ASCII, the most common code For example, Java source files are text files It is any file created with a "text editor" Binary files: the bits represent other types of encoded information, such as executable instructions or numeric data These files are easily read by the computer but not humans They are not "printable" files Actually, you can print them, but they will be unintelligible "printable" means "easily readable by humans when printed"

Java: Text vs Binary Files 12 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O Text files are more readable by humans Binary files are more efficient computers read and write binary files more easily than text Java binary files are portable They can be used by Java on different machines Reading and writing binary files is normally done by a program Text files are used only to communicate with humans Java Text Files Source files Occasionally input files Occasionally output files Java Binary Files Executable files (created by compiling source files) Usually input files Usually output files

Text Files vs Binary Files 13 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O Number: 127 (decimal) Text file: Three bytes: “1”, “2”, “7” ASCII (decimal): 49, 50, 55 ASCII (octal): 61, 62, 67 ASCII (binary): , , Binary file: One byte (byte): Two bytes (short): Four bytes (int):

Text File I/O 14 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O Important classes for text file output (to the file): PrintWriter FileOutputStream [or FileWriter] Important classes for text file input (from the file): BufferedReader FileReader FileOutputStream and FileReader take file names as arguments PrintWriter and BufferedReader provide useful methods for easier writing and reading Usually need a combination of two classes To use these classes your program needs a line like the following: import java.io.*;

Every File Has Two Names 15 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O The stream name used by Java outputStream in the example The name used by the operating system out.txt in the example

Text File Output 16 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O To open a text file for output: connect a text file to a stream for writing PrintWriter outputStream = new PrintWriter(new FileOutputStream("out.txt")); Similar to the long way: FileOutputStream s = new FileOutputStream("out.txt"); PrintWriter outputStream = new PrintWriter(s); Goal: create a PrintWriter object Which uses FileOutputStream to open a text file FileOutputStream “connects” PrintWriter to a text file

Output File Streams 17 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O PrintWriter FileOutputStream Disk Memory smileyOutStream smiley.txt PrintWriter smileyOutStream = new PrintWriter( new FileOutputStream(“smiley.txt”) );

Methods for PrintWriter 18 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O Similar to methods for System.out println outputStream.println(count + " " + line); print format flush: write buffered output to disk close: close the PrintWriter stream (and file)

I/O Class Hierarchy 19 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O class java.lang.ObjectObject class java.io.InputStreamInputStream class java.io.ByteArrayInputStreamByteArrayInputStream class java.io.FileInputStreamFileInputStream class java.io.FilterInputStreamFilterInputStream class java.io.OutputStreamOutputStream class java.io.ByteArrayOutputStreamByteArrayOutputStream class java.io.FileOutputStreamFileOutputStream class java.io.FilterOutputStreamFilterOutputStream class java.io.ReaderReader class java.io.BufferedReaderBufferedReader … class java.io.InputStreamReaderInputStreamReader class java.io.WriterWriter class java.io.BufferedWriterBufferedWriter … class java.io.OutputStreamWriterOutputStreamWriter

I/O Exceptions 20 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O CharConversionException EOFException FileNotFoundException InterruptedIOException InvalidClassException InvalidObjectException NotActiveException NotSerializableException ObjectStreamException OptionalDataException StreamCorruptedException SyncFailedException UnsupportedEncodingException UTFDataFormatException WriteAbortedException

Text File Output Demo 21 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O public static void main(String[ ] args) { PrintWriter outputStream = null; try { outputStream = new PrintWriter(new FileOutputStream("out.txt")); } catch(FileNotFoundException e) { System.out.println("Error opening the file out.txt.” + e.getMessage()); System.exit(0); }

Text File Output Demo 22 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O System.out.println("Enter three lines of text:"); String line = null; int count; Scanner keyword = new Scanner(System.in); for (count = 1; count <= 3; count++) { line = keyboard.nextLine(); outputStream.println(count + " " + line); } outputStream.close(); System.out.println("... written to out.txt."); }

Appending to a Text File 23 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O To add/append to a file instead of replacing it, use a different constructor for FileOutputStream: outputStream = new PrintWriter(new FileOutputStream("out.txt", true)); Second parameter: append to the end of the file if it exists? Sample code for letting user tell whether to replace or append:

Appending to a Text File 24 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O System.out.println("A for append or N for new file:"); char ans = keyboard.next().charAt(0); boolean append = (ans == 'A' || ans == 'a'); outputStream = new PrintWriter( new FileOutputStream("out.txt", append)); true if user enters 'A'

Closing a File 25 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O An output file should be closed when you are done writing to it (and an input file should be closed when you are done reading from it) Use the close method of the class PrintWriter (BufferedReader also has a close method) For example, to close the file opened in the previous example: outputStream.close(); If a program ends normally it will close any files that are open

Text File Input 26 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O To open a text file for input: connect a text file to a stream for reading Goal: a BufferedReader object, Which uses FileReader to open a text file FileReader “connects” BufferedReader to the text file For example: BufferedReader smileyInStream = new BufferedReader(new FileReader(“smiley.txt")); Similarly, the long way: FileReader s = new FileReader(“smiley.txt"); BufferedReader smileyInStream = new BufferedReader(s);

Input File Streams 27 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O BufferedReader FileReader Disk Memory smileyInStream smiley.txt BufferedReader smileyInStream = new BufferedReader( new FileReader(“smiley.txt”) );

Methods for BufferedReader 28 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O readLine: read a line into a String No methods to read numbers directly, so read numbers as Strings and then convert them (StringTokenizer later) read: read a char at a time close: close BufferedReader stream

Text File Input Demo 29 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O public static void main(String[] args) { String fileName = null; // outside try block, can be used in catch try { Scanner keyboard = new Scanner(System.in); System.out.println("Enter file name:"); fileName = keyboard.next(); BufferedReader inputStream = new BufferedReader(new FileReader(fileName)); String line = null; line = inputStream.readLine(); System.out.println("The first line in " + filename + " is:"); System.out.println(line); //... code for reading second line not shown here... inputStream.close(); }

Text File Input Demo 30 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O catch (FileNotFoundException e) { System.out.println("File " + filename + " not found."); } catch (IOException e) { System.out.println("Error reading from file " + fileName); }

Using Path Names 31 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O Path name: gives name of file and tells which directory the file is in Relative path name: gives the path starting with the directory that the program is in Typical UNIX path name: /user/smith/home.work/java/FileClassDemo.java Typical Windows path name: D:\Work\Java\Programs\FileClassDemo.java When a backslash is used in a quoted string it must be written as two backslashes since backslash is the escape character: "D:\\Work\\Java\\Programs\\FileClassDemo.java" Java will accept path names in UNIX or Windows format, regardless of which operating system it is actually running on

File Class 32 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O Acts like a wrapper class for file names A file name like "numbers.txt" has only String properties File has some very useful methods: boolean exists(): tests if a file already exists boolean canRead(): tests if the OS will let you read a file boolean canWrite(): tests if the OS will let you write to a file delete(): deletes the file, returns true if successful long length(): returns the number of bytes in the file String getName(): returns file name, excluding the preceding path String getPath(): returns the path name - the full name

File Class 33 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O String getParent(): Returns a String with the parent directory of the file or directory String getAbsolutePath(): Returns a String with the absolute path of the file or directory String[] list(): Returns an array of Strings representing a directory’s contents boolean isFile(): Returns true if the name specified as the argument to the File constructor is a file; false otherwise boolean isDirectory(): Returns true if the name specified as the argument to the File constructor is a directory; false otherwise boolean isAbsolute(): Returns true if the arguments specified to the File constructor indicate an absolute path to a file or directory; false otherwise

Demo to Obtain File and Directory Information 34 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O

Basic Binary File I/O 35 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O Important classes for binary file output (to the file): ObjectOutputStream FileOutputStream Important classes for binary file input (from the file): ObjectInputStream FileInputStream Note that FileOutputStream and FileInputStream are used only for their constructors, which can take file names as arguments ObjectOutputStream and ObjectInputStream cannot take file names as arguments for their constructors To use these classes your program needs a line like the following: import java.io.*;

Opening Files With JFileChooser 36 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JFileChooser;

Opening Files With JFileChooser 37 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O public class JFileChosser2 extends JFrame { private JTextArea outputArea; // used for output private JScrollPane scrollPane; // used to provide scrolling to output // set up GUI public JFileChosser2() { super( "Testing class File" ); outputArea = new JTextArea(); // add outputArea to scrollPane scrollPane = new JScrollPane( outputArea ); add( scrollPane, BorderLayout.CENTER ); // add scrollPane to GUI setSize( 400, 400 ); // set GUI size setVisible( true ); // display GUI analyzePath(); // create and analyze File object } // end FileDemonstration constructor // allow user to specify file or directory name

Opening Files With JFileChooser 38 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O private File getFileOrDirectory() { JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode( JFileChooser.FILES_AND_DIRECTORIES ); int result = fileChooser.showOpenDialog(this); // if user clicked Cancel button on dialog, return if (result==JFileChooser.CANCEL_OPTION) System.exit( 1 ); File fileName = fileChooser.getSelectedFile(); // get File // display error if invalid if ( ( fileName == null ) || ( fileName.getName().equals( "" ))) { JOptionPane.showMessageDialog( this, "Invalid Name", "Invalid Name", JOptionPane.ERROR_MESSAGE ); System.exit( 1 ); } // end if return fileName; } // end method getFile // display information about file or directory user specifies

Opening Files With JFileChooser 39 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O public void analyzePath() { // create File object based on user input File name = getFileOrDirectory(); if ( name.exists() ) // if name exists, output information about it { // display file (or directory) information outputArea.setText( String.format( "%s%s\n%s\n%s\n%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s ", name.getName(), " exists", ( name.isFile() ? "is a file" : "is not a file" ), ( name.isDirectory() ? "is a directory" : "is not a directory" ), ( name.isAbsolute() ? "is absolute path" : "is not absolute path" ), "Last modified: ", name.lastModified(), "Length: ", name.length(), "Path: ", name.getPath(), "Absolute path: ", name.getAbsolutePath(), "Parent: ", name.getParent() ) ); if ( name.isDirectory() ) // output directory listing

Opening Files With JFileChooser 40 9/9/2019 Estifanos T. (MSc in Computer Networking) Lecture 2: Streams and File I/O { String[] directory = name.list(); outputArea.append( "\n\nDirectory contents:\n" ); for ( String directoryName : directory ) outputArea.append( directoryName + "\n" ); } // end else } // end outer if else // not file or directory, output error message { JOptionPane.showMessageDialog( this, name + " does not exist.", "ERROR", JOptionPane.ERROR_MESSAGE ); } // end else } // end method analyzePath public static void main( String[] args ) { JFileChosser2 application = new JFileChosser2(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } // end main } // end class FileDemonstrationTest

End Of Chapter Two