Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Java Chapter 2 (Estifanos Tilahun Mihret--Tech with Estif)"— Presentation transcript:

1 Advanced Programming Estifanos T. (MSc in Computer Networking)

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

3 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

4 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

5 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

6 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

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

8 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)

9 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

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

11 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"

12 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

13 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): 00110001, 00110010, 00110111 Binary file: One byte (byte): 01111110 Two bytes (short): 00000000 01111110 Four bytes (int): 00000000 00000000 00000000 01111110

14 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.*;

15 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

16 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

17 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”) );

18 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)

19 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

20 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

21 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); }

22 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."); }

23 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:

24 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'

25 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

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

27 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”) );

28 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

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

30 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); }

31 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

32 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

33 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

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

35 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.*;

36 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;

37 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

38 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

39 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

40 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

41 End Of Chapter Two


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

Similar presentations


Ads by Google