Lecture 7. File Processing
|
|
- Stuart Roberts
- 6 years ago
- Views:
Transcription
1 Lecture 7 File Processing 1
2 Data (i.e., numbers and strings) stored in variables, arrays, and objects are temporary. They are lost when the program terminates. To permanently store the data created in a program, you need to save them in a file on a disk. 2
3 Lecture Content 1. Text File 2. Binary File 3. Random-Access File 4. Binary I/O of Class Objects 3
4 1. Text File In general, I/O classes for file processing can be classified as input classes and output classes. An input class contains the methods to read data from a file. - Scanner is an example of an input class. An output class contains the methods to write data to a file. - PrintWriter is an example of an output class. 4
5 1. Text File An input object reads a stream of data from a file. - An input object is called an input stream. An output object writes a stream of data to a file. - An output object is called an output stream. This section presents how to read/write strings and numeric values to/from a text file using the Scanner and PrintWriter classes. 5
6 1. Text File The program receives data through an input object and sends data through an output object. Scanner PrintWriter 6
7 Writing Data Using PrintWriter import java.io.printwriter; import java.io.file; public class Ex1 { public static void main(string[] args) throws Exception { // Create file object in memory // The file named Ex1Out.txt does not // exist on disk File file = new File("Ex1Out.txt"); 7
8 Writing Data Using PrintWriter // Create a file on disk PrintWriter fo = new PrintWriter(file); // we can use PrintWriter fo = // new PrintWriter("Ex1Out.txt); // Write formatted output to the file fo.print("john T Smith "); fo.println(90); // integer number 8
9 Writing Data Using PrintWriter } } fo.print("eric K Jones "); fo.println(85); System.out.println( "File writing is done."); // Close the file fo.close(); 9
10 Writing Data Using PrintWriter Invoking the constructor of PrintWriter will create a new file if the file does not exist. - If the file already exists, the current content in the file will be discarded (empty file exists). if (file.exists() == true) { System.out.println( File already exists."); System.exit(0); } 10
11 Writing Data Using PrintWriter Invoking the constructor of PrintWriter may throw an I/O exception. - Java forces you to write the code to deal with this type of exception. Simply declare throws Exception in the method. The close() method must be used to close the file. If this method is not invoked, the data may not be saved properly in the file. 11
12 Methods of the PrintWriter Class. 12
13 Reading Data Using Scanner import java.util.scanner; import java.util.file; public class Ex2 { public static void main(string[] args) throws Exception { // Create a File instance File file = new File("Ex1Out.txt"); // Create a Scanner for the file Scanner fi = new Scanner(file); 13
14 Reading Data Using Scanner // Read data from a file while (fi.hasnext()) { // while not end of file String firstname = fi.next(); String middlename = fi.next(); String lastname = fi.next(); int score = fi.nextint(); System.out.println( firstname + " " + middlename + " " + lastname + " " + score); } 14
15 Reading Data Using Scanner } } System.out.println( "File reading is done."); // Close the file fi.close(); 15
16 Reading Data Using Scanner Invoking the constructor new Scanner(file) may throw an I/O exception. Thus, the main() method declares throws Exception. To create a Scanner to read data from a file, you must use the java.io.file class to create an instance of the File by using the constructor new File(filename), and use new Scanner(file) to create a Scanner for the file. 16
17 Reading Data Using Scanner Each iteration in the while loop reads first name, middle name, last name, and score from the text file. Finally, the file is closed. It is not necessary to close the input file, but it is a good practice to do so to release the resources occupied by the file. 17
18 Methods of the Scanner Class. 18
19 StringTokenizer import java.util.stringtokenizer;... String inputline; StringTokenizer parser; String name; double score; while ( fi.hasnext() ) { // while not end of file inputline = fi.nextline(); parser = new StringTokenizer(inputLine); try { 19
20 StringTokenizer name = parser.nexttoken() + " " + parser.nexttoken() + " " + parser.nexttoken(); score = Double.parseDouble( parser.nexttoken() ); System.out.printf("%s %.2f\n", name, score); } catch (NoSuchElementException e) { // no token System.out.println(e); } } fi.close(); 20
21 Lecture Content 1. Text File 2. Binary File 3. Random-Access File 4. Binary I/O of Class Objects 21
22 2. Binary File This section introduces the classes for performing binary I/O. Data stored in a text file are represented in humanreadable form. Data stored in a binary file are represented in binary form. You cannot read binary files. They are designed to be read by programs. 22
23 2. Binary File The advantage of binary files is that they are more efficient to process than text files. Example: The decimal integer 199 is stored as the sequence of three characters, 1, 9, 9, in a text file, and the same integer is stored as a byte-type value C7 in a binary file, because decimal 199 equals hexadecimal number C7 ( ). 23
24 2. Binary File Text I/O requires encoding and decoding whereas binary I/O does not, as shown below. 24
25 2. Binary File Text I/O requires encoding and decoding whereas binary I/O does not, as shown below. 25
26 2. Binary File The ASCII code for character 1 is 49 (0x31 in hex) and for character 9 is 57 (0x39 in hex). So to write the characters 199, three bytes 0x31, 0x39, and 0x39 are sent to the output, as shown above. Binary I/O is more efficient than text I/O, because binary I/O does not require encoding and decoding. 26
27 2. Binary File Some of the classes for performing binary I/O are listed below. 27
28 2. Binary File FileOutputStream is for writing bytes to a file (i.e., byte-based output). - If the file does not exist, a new file will be created. If the file already exists, the current content of the file will deleted. - To retain the current content and append new data into the file, use true for the append parameter. 28
29 2. Binary File FileInputStream is for reading bytes from a file (i.e., byte-based input). Almost all the methods in the I/O classes throw java.io.ioexception. Therefore you have to declare java.io.ioexception to throw in the method or place the code in a try-catch block, as shown below: 29
30 2. Binary File. 30
31 FileOutputStream / FileInputStream Example: uses binary I/O (i.e., FileOutputStream and FileInputStream) to write ten byte values from 1 to 10 to a file named Ex5Out.dat and reads them back from the file. 31
32 FileOutputStream / FileInputStream //import java.io.ioexception; //import java.io.fileoutputstream; //import java.io.fileinputstream; import java.io.*; public class Ex5 { public static void main(string[] args) throws IOException { // Create an output stream to the file FileOutputStream fo = new FileOutputStream("Ex5Out.dat"); 32
33 FileOutputStream / FileInputStream // Output values to the file for (int i = 1; i <= 10; i++) fo.write(i); // Close the output stream fo.close(); // Create an input stream for the file FileInputStream fi = new FileInputStream("Ex5Out.dat"); // Read values from the file int value; 33
34 FileOutputStream / FileInputStream } } while ((value = fi.read())!= -1) // while not end of file System.out.print(value + " "); System.out.println(); // Close the output stream fi.close(); 34
35 Methods of FileOutputStream Class. Weakness? - byte-based write 35
36 Methods of FileInputStream Class. Weakness? - byte-based read 36
37 DataInputStream / DataOutputStream DataInputStream reads bytes from the stream and converts them into appropriate primitive type values or strings. DataOutputStream converts primitive type values or strings into bytes and outputs the bytes to the stream. 37
38 DataInputStream / DataOutputStream Primitive values are copied from memory to the output without any conversions. The writeutf(string s) method converts a string into a series of bytes in the UTF-8 format and writes them into a binary stream. The readutf() method reads a string that has been written using the writeutf method. 38
39 DataInputStream / DataOutputStream Two character encoding schemes are ASCII (American Standard Code for Information Interchange, 1 byte) code and UTF (Unicode Transformation Format, UTF-8, UTF-16, UTF-32) code. 39
40 DataInputStream / DataOutputStream Example: writes student names and scores to a file named Ex6Out.dat and reads the data back from the file. 40
41 DataInputStream / DataOutputStream import java.io.*; public class Ex6 { // process primitive numeric types, strings public static void main(string[] args) throws IOException { // Create output stream for Ex6Out.dat DataOutputStream fo = new DataOutputStream( new FileOutputStream("Ex6Out.dat")); 41
42 DataInputStream / DataOutputStream // Write student test scores to the file fo.writeutf("john"); fo.writedouble(85.5); fo.writeutf("jim"); fo.writedouble(185.5); fo.writeutf("george"); fo.writedouble(105.25); // Close output stream fo.close(); 42
43 DataInputStream / DataOutputStream // Create input stream for Ex6Out.dat DataInputStream fi = new DataInputStream( new FileInputStream("Ex6Out.dat")); 43
44 DataInputStream / DataOutputStream } } // Read student test scores from file System.out.println(fi.readUTF() + " " + fi.readdouble()); System.out.println(fi.readUTF() + " " + fi.readdouble()); System.out.println(fi.readUTF() + " " + fi.readdouble()); // Close input stream fi.close(); 44
45 DataInputStream / DataOutputStream // Ex6_2 // Read student test scores from file boolean stop = false; while (!stop) try { System.out.println(fi.readUTF() + " " + fi.readdouble()); } catch (IOException ex) { stop = true; } 45
46 Methods of DataOutputStream Class. 46
47 Methods of DataInputStream Class. 47
48 Object I/O DataInputStream and DataOutputStream enable you to perform I/O for primitive type values and strings. ObjectInputStream and ObjectOutputStream enable you to perform I/O for objects in addition to primitive type values and strings. 48
49 ObjectOutputStream import java.io.*; public class Ex7 { // Test ObjectOutputStream and writeobject() public static void main(string[] args) throws IOException { // Create output stream for Ex7Out.dat ObjectOutputStream fo = new ObjectOutputStream( new FileOutputStream("Ex7Out.dat")); 49
50 ObjectOutputStream } } // Write a string, double value, and // object to the file fo.writeutf("john"); fo.writedouble(85.5); fo.writeobject(new java.util.date()); // write Date object, // Mon Feb 04 22:22:54 GMT-04: System.out.println( "File writing is done."); fo.close(); // Close output stream 50
51 ObjectInputStream import java.io.*; public class Ex8 { // Test ObjectInputStream and readobject() public static void main(string[] args) throws ClassNotFoundException, IOException { // Create input stream for Ex7Out.dat ObjectInputStream fi = new ObjectInputStream( new FileInputStream("Ex7Out.dat")); 51
52 ObjectInputStream // Read a string, double value, and // object to the file String name = fi.readutf(); double score = fi.readdouble(); java.util.date date = (java.util.date)(fi.readobject()); System.out.println(name + " " + score + " " + date); // read Date object // Mon Feb 04 22:22:54 GMT-04: System.out.println( "File reading is done."); 52
53 ObjectInputStream } } // Close output stream fi.close(); 53
54 Object I/O The readobject() method may throw java.lang.classnotfoundexception if the class for the object has not been loaded. Since readobject() returns an Object, it is cast into Date and assigned to a date variable. 54
55 Serialization / Deserialization Object serialization is implemented in ObjectOutputStream so that an object can be written to an output stream (called serializable object). Object deserialization is implemented in ObjectInputStream so that an object can be read from an input stream. 55
56 Write/Read int and String Arrays Example: Write and read entire int array and String array 56
57 Write/Read int and String Arrays public class Ex9 { // Test ObjectStream for int and String // arrays public static void main(string[] args) throws ClassNotFoundException, IOException { int[] numbers = {1, 2, 3, 4, 5}; String[] strings = {"John", "Jim", "Jake"}; 57
58 Write/Read int and String Arrays // Create output stream for Ex9Out.dat ObjectOutputStream fo = new ObjectOutputStream( new FileOutputStream( "Ex9Out.dat", true)); // Write arrays to object output stream fo.writeobject(numbers); // int array fo.writeobject(strings); // String array // Close the stream fo.close(); 58
59 Write/Read int and String Arrays // Create input stream for Ex9Out.dat ObjectInputStream fi = new ObjectInputStream( new FileInputStream( "Ex9Out.dat")); int[] newnumbers = (int[])(fi.readobject()); String[] newstrings = (String[])(fi.readObject()); 59
60 Write/Read int and String Arrays } } // Display int and String arrays for (int i = 0; i < newnumbers.length; i++) System.out.print(newNumbers[i] + " "); System.out.println(); for (int i = 0; i < newstrings.length; i++) System.out.print(newStrings[i] + " "); System.out.println(); fi.close(); // Close the stream 60
61 ObjectOutputStream ObjectOutputStream can write objects, primitive type values, and strings. 61
62 ObjectInputStream ObjectInputStream can read objects, primitive type values, and strings. 62
63 Lecture Content 1. Text File 2. Binary File 3. Random-Access File 4. Binary I/O of Class Objects 63
64 3. Random-Access File Text file (human-readable) and binary file (machine-readable) discussed above are sequential files. Random-access file (machine-readable) can be written to and read from at random locations. RandomAccessFile class allows a file to be read from and written to at random locations. 64
65 3. Random-Access File The RandomAccessFile class implements the DataInput and DataOutput interfaces, as shown in Figure below. 65
66 Methods of RandomAccessFile Class. 66
67 3. Random-Access File The DataInput interface defines the methods (e.g., readint(), readdouble(), readchar(), readutf()) for reading primitive type values and strings. The DataOutput interface defines the methods (e.g., writeint(), writedouble(), writechar(), writeutf()) for writing primitive type values and strings. 67
68 3. Random-Access File Random-access file can be created with two modes as follows. RandomAccessFile fio = new RandomAccessFile( "Test.dat", "rw"); RandomAccessFile fio = new RandomAccessFile( "Test.dat", "r"); 68
69 File Pointer A random-access file consisting of a sequence of bytes has a special marker called a file pointer positioned at one of these bytes. - A read or write operation takes place at the location of the file pointer. - When a file is opened, the file pointer is set at the beginning of the file (i.e., byte 0). 69
70 File Pointer - When you read or write data to the file, the file pointer moves forward to the next data item (not the next byte). - For example, if you read an int value using readint(), the JVM reads 4 bytes from the file pointer, and now the file pointer is 4 bytes ahead of the previous location, as shown in Figure below. 70
71 File Pointer (a) Before readint() (b) After readint() After an int value is read, the file pointer is moved 4 bytes ahead. 71
72 3. Random-Access File //import java.io.randomaccessfile; import java.io.*; public class Ex10 { // Test RandomAccessFile public static void main(string[] args) throws IOException { int n = 9, i = 0; 72
73 3. Random-Access File // Create a random access file RandomAccessFile fio = new RandomAccessFile( "Ex10InOut.dat", "rw"); // Clear the file to destroy old // contents if exists fio.setlength(0); // Write integers to file for (int j = 1; j <= n; j++) fio.writeint(j); 73
74 3. Random-Access File // Display current length of file System.out.println( "Current file length is " + fio.length()); // Retrieve the first number // Move file pointer to the beginning fio.seek(0); System.out.println( "The first number is " + fio.readint()); 74
75 3. Random-Access File // Retrieve the second number // Move fp to the second number fio.seek(1 * 4); System.out.println( "The second number is " + fio.readint()); // Retrieve the sixth number // Move file pointer to the sixth number fio.seek(5 * 4); 75
76 3. Random-Access File System.out.println( "The sixth number is " + fio.readint()); // Modify the seventh number fio.writeint(55); // Append a new number // Move file pointer to the end fio.seek(fio.length()); fio.writeint(99); 76
77 3. Random-Access File } } // Display the new length System.out.println( "The new length is " + fio.length()); // Retrieve the new seventh number // Move fp to the seventh number fio.seek(6 * 4); System.out.println( "The seventh number is " + fio.readint()); fio.close(); 77
78 Lecture Content 1. Text File 2. Binary File 3. Random-Access File 4. Binary I/O of Class Objects 78
79 4. Binary I/O of Class Objects A class object can be written to and read from a binary file by making the class implement the Serializable interface as follows. public class SomeClass implements Serializable { }... 79
80 4. Binary I/O of Class Objects To write an object of a class such as SomeClass to a binary file, you simply use the writeobject() method of the stream class ObjectOutputStream. If an object is written to a binary file with the writeobject() method, then the object can be read from the file with the readobject() method of the stream class ObjectInputStream. 80
81 4. Binary I/O of Class Objects The readobject() method returns an object of type Object. Thus, if you want to obtain an object of type SomeClass, you must do a type cast as follows. SomeClass u = (SomeClass)fi.readObject(); Example : Write and read class objects to/from a binary file using writeobject() and readobject() methods. 81
82 4. Binary I/O of Class Objects import java.io.ioexception; import java.io.objectoutputstream; import java.io.fileoutputstream; import java.io.objectinputstream; import java.io.fileinputstream; import java.io.filenotfoundexception; import java.io.serializable; 82
83 4. Binary I/O of Class Objects class SomeClass implements Serializable { // Serializable class private int number; private char letter; public SomeClass() { number = 0; letter = 'A'; } 83
84 4. Binary I/O of Class Objects public SomeClass(int thenumber, char theletter) { number = thenumber; letter = theletter; } 84
85 4. Binary I/O of Class Objects } public String tostring() { // if we omit this method, // the memory address of class // object will be output return "Number = " + number + " Letter = " + letter; } 85
86 4. Binary I/O of Class Objects public class Ex11 { // Test Binary I/O of class objects public static void main(string[] args) throws IOException, ClassNotFoundException { ObjectOutputStream fo = new ObjectOutputStream( new FileOutputStream( "Ex11Out.dat")); 86
87 4. Binary I/O of Class Objects SomeClass x = new SomeClass(1, 'A'); SomeClass y = new SomeClass(42, 'Z'); fo.writeobject(x); fo.writeobject(y); fo.close(); System.out.println( "class objects were sent to file."); 87
88 4. Binary I/O of Class Objects System.out.println( "Now let's reopen the file and display the data."); ObjectInputStream fi = new ObjectInputStream( new FileInputStream( "Ex11Out.dat")); // You must perform type cast SomeClass u = (SomeClass)fi.readObject(); SomeClass v = (SomeClass)fi.readObject(); 88
89 4. Binary I/O of Class Objects } } System.out.println( "The following objects were read from the file:"); System.out.println(u); System.out.println(v); System.out.println("End of program."); 89
90 Binary I/O of Array Object An array is an object. Thus, an entire array can be saved to a binary file using writeobject() and later read using readobject(). If the array has a base type that is a class (e.g., SomeClass), then the class must be serializable. Note that the type cast (SomeClass[]) must be used to obtain the correct data read by readobject(). 90
91 Binary I/O of Array of Objects Example: Write and read an array of objects to/from a binary file using writeobject() and (SomeClass[])fi.readObject(). 91
92 Binary I/O of Array of Objects import java.io.*; class SomeClass implements Serializable { // Serializable class... } public class Ex12 { public static void main(string[] args) throws IOException, ClassNotFoundException { 92
93 Binary I/O of Array of Objects SomeClass[] a = new SomeClass[2]; a[0] = new SomeClass(1, 'A'); a[1] = new SomeClass(2, 'B'); ObjectOutputStream fo = new ObjectOutputStream( new FileOutputStream( "Ex12Out.dat")); fo.writeobject(a); fo.close(); System.out.println( "Array object was written to file."); 93
94 Binary I/O of Array of Objects System.out.println( "Now let's reopen the file and display the array."); SomeClass[] b = null; ObjectInputStream fi = new ObjectInputStream( new FileInputStream( "Ex12Out.dat")); b = (SomeClass[])fi.readObject(); fi.close(); 94
95 Binary I/O of Array of Objects } } System.out.println( "The following array elements were read from the file:"); for (int i = 0; i < b.length; i++) System.out.println(b[i]); System.out.println("End of program."); 95
96 Programming Project Use topics taught in the class to write a simple program of student management system using an array of objects. You need to read/write the student list from/to text and binary files. 96
97 Programming Project Required functionalities are as follows. 1. Input student list 2. Output student list 3. Add a new student 4. Search a student a. Search on given last name b. Search on given student ID 97
98 Programming Project Required functionalities are as follows. 5. Delete a student with a given student ID 6. Update a student with a given student ID 7. Sort on last name or average mark c. Sort on average mark d. Sort on last name 8. Exit 98
99 Programming Project The student data are as follows class Student { public String sid; // student ID public String sname; // student name (First Middle Last) int[] m; // marks of 3 courses, belong to [0..100] double avg; // average mark with 2 digits after decimal point // constructors and methods } // end class Student 99
100 References 1. Y. Daniel Liang Introduction to Java Programming, Comprehensive. 10 th Ed. Pearson. ISBN: Paul Deitel, Harvey Deitel Java How to Program. 10 th Ed. Pearson. ISBN: Water Savitch, Kenrich Mock Absolute Java. 6 th Ed. Pearson. ISBN:
Chapter 10. File I/O. Copyright 2016 Pearson Inc. All rights reserved.
Chapter 10 File I/O Copyright 2016 Pearson Inc. All rights reserved. Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program,
More informationChapter 17 Binary I/O. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved.
Chapter 17 Binary I/O 1 Motivations Data stored in a text file is represented in human-readable form. Data stored in a binary file is represented in binary form. You cannot read binary files. They are
More informationPrevious to Chapter 7 Files
Previous to Chapter 7 Files Recall Scanner from Part I notes. A scanner object can reference a text file Scanner f = new Scanner(new File("file name goes here")); Scanner methods can be applied to reading
More informationCS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University
CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Files Two types: Text file and Binary file Text file (ASCII file) The file data contains only ASCII values
More informationFile IO. Binary Files. Reading and Writing Binary Files. Writing Objects to files. Reading Objects from files. Unit 20 1
File IO Binary Files Reading and Writing Binary Files Writing Objects to files Reading Objects from files Unit 20 1 Binary Files Files that are designed to be read by programs and that consist of a sequence
More informationCS 251 Intermediate Programming Java I/O Streams
CS 251 Intermediate Programming Java I/O Streams Brooke Chenoweth University of New Mexico Spring 2018 Basic Input/Output I/O Streams mostly in java.io package File I/O mostly in java.nio.file package
More informationCPIT 305 Advanced Programming
M. G. Abbas Malik CPIT 305 Advanced Programming mgmalik@uj.edu.sa Assistant Professor Faculty of Computing and IT University of Jeddah Advanced Programming Course book: Introduction to Java Programming:
More informationData Structures. 03 Streams & File I/O
David Drohan Data Structures 03 Streams & File I/O JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN 0132162709 2012 Pearson Education, Inc., Upper Saddle River, NJ.
More informationJava How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.
Java How to Program, 9/e Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Data stored in variables and arrays is temporary It s lost when a local variable goes out of scope or when
More information14.3 Handling files as binary files
14.3 Handling files as binary files 469 14.3 Handling files as binary files Although all files on a computer s hard disk contain only bits, binary digits, we say that some files are text files while others
More informationStarting Out with Java: From Control Structures Through Objects Sixth Edition
Starting Out with Java: From Control Structures Through Objects Sixth Edition Chapter 11 I/O File Input and Output Reentering data all the time could get tedious for the user. The data can be saved to
More informationStreams and File I/O
Chapter 9 Streams and File I/O Overview of Streams and File I/O Text File I/O Binary File I/O File Objects and File Names Chapter 9 Java: an Introduction to Computer Science & Programming - Walter Savitch
More informationStreams and File I/O
Walter Savitch Frank M. Carrano Streams and File I/O Chapter 10 Objectives Describe the concept of an I/O stream Explain the difference between text and binary files Save data, including objects, in a
More informationJava Programming Lecture 9
Java Programming Lecture 9 Alice E. Fischer February 16, 2012 Alice E. Fischer () Java Programming - L9... 1/14 February 16, 2012 1 / 14 Outline 1 Object Files Using an Object File Alice E. Fischer ()
More informationExceptions Binary files Sequential/Random access Serializing objects
Advanced I/O Exceptions Binary files Sequential/Random access Serializing objects Exceptions No matter how good of a programmer you are, you can t control everything. Other users Available memory File
More informationChapter 11: Exceptions and Advanced File I/O
Chapter 11: Exceptions and Advanced File I/O Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 11 discusses the following main topics:
More informationBasic I/O - Stream. Java.io (stream based IO) Java.nio(Buffer and channel-based IO)
I/O and Scannar Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 I/O operations Three steps:
More information7 Streams and files. Overview. Binary data vs text. Binary data vs text. Readers, writers, byte streams. input-output
Overview 7 Streams and files import java.io.*; Binary data vs textual data Simple file processing - examples The stream model Bytes and characters Buffering Byte streams Character streams Binary streams
More informationCN208 Introduction to Computer Programming
CN208 Introduction to Computer Programming Lecture #11 Streams (Continued) Pimarn Apipattanamontre Email: pimarn@pimarn.com 1 The Object Class The Object class is the direct or indirect superclass of every
More informationChapter 12: Exceptions and Advanced File I/O
Chapter 12: Exceptions and Advanced File I/O Starting Out with Java: From Control Structures through Objects Fourth Edition by Tony Gaddis Addison Wesley is an imprint of 2010 Pearson Addison-Wesley. All
More informationPerforming input and output operations using a Byte Stream
Performing input and output operations using a Byte Stream public interface DataInput The DataInput interface provides for reading bytes from a binary stream and reconstructing from them data in any of
More informationOptional Lecture Chapter 17 Binary IO
Optional Lecture Chapter 17 Binary IO COMP217 Java Programming Spring 2017 Text: Liang, Introduction to Java Programming, 10 th Edition Chapter 17 Binary IO 1 Motivations Data stored in a text file is
More informationCS112 Lecture: Streams
CS112 Lecture: Streams Objectives: Last Revised March 30, 2006 1. To introduce the abstract notion of a stream 2. To introduce the java File, Input/OutputStream, and Reader/Writer abstractions 3. To show
More informationJob Migration. Job Migration
Job Migration The Job Migration subsystem must provide a mechanism for executable programs and data to be serialized and sent through the network to a remote node. At the remote node, the executable programs
More informationWeek 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O
Week 12 Streams and File I/O Overview of Streams and File I/O Text File I/O 1 I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or a file
More informationI/O Streams. Object-oriented programming
I/O Streams Object-oriented programming Outline Concepts of Data Streams Streams and Files File class Text file Binary file (primitive data, object) Readings: GT, Ch. 12 I/O Streams 2 Data streams Ultimately,
More informationChapter 12. File Input and Output. CS180-Recitation
Chapter 12 File Input and Output CS180-Recitation Reminders Exam2 Wed Nov 5th. 6:30 pm. Project6 Wed Nov 5th. 10:00 pm. Multitasking: The concurrent operation by one central processing unit of two or more
More informationInput, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003
Input, Output and Exceptions COMS W1007 Introduction to Computer Science Christopher Conway 24 June 2003 Input vs. Output We define input and output from the perspective of the programmer. Input is data
More informationSchool of Informatics, University of Edinburgh
CS1Ah Lecture Note 29 Streams and Exceptions We saw back in Lecture Note 9 how to design and implement our own Java classes. An object such as a Student4 object contains related fields such as surname,
More informationWhat is Serialization?
Serialization 1 Topics What is Serialization? What is preserved when an object is serialized? Transient keyword Process of serialization Process of deserialization Version control Changing the default
More informationSTREAMS. (fluxos) Objetivos
STREAMS (fluxos) Objetivos To be able to read and write files To become familiar with the concepts of text and binary files To be able to read and write objects using serialization To be able to process
More informationBinary I/O. CSE 114, Computer Science 1 Stony Brook University
Binary I/O CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 Motivation Data stored in a text files is represented in humanreadable form Data stored in a binary files
More informationProgrammierpraktikum
Programmierpraktikum Claudius Gros, SS2012 Institut für theoretische Physik Goethe-University Frankfurt a.m. 1 of 21 05/07/2012 10:31 AM Input / Output Streams 2 of 21 05/07/2012 10:31 AM Java I/O streams
More informationFILE I/O IN JAVA. Prof. Chris Jermaine
FILE I/O IN JAVA Prof. Chris Jermaine cmj4@cs.rice.edu 1 Our Simple Java Programs So Far Aside from screen I/O......when they are done, they are gone They have no lasting effect on the world When the program
More information输 入输出相关类图. DataInput. DataOutput. java.lang.object. FileInputStream. FilterInputStream. FilterInputStream. FileOutputStream
输 入 / 输出 杨亮 流的分类 输 入输出相关类图 OutputStream FileOutputStream DataInputStream ObjectOutputStream FilterInputStream PipedOutputStream DataOutput InputStream DataInputStream PrintStream ObjectInputStream PipedInputStream
More informationCPS122 Lecture: Input-Output
CPS122 Lecture: Input-Output Objectives: Last Revised January 19, 2010 1. To discuss IO to System.in/out/err 2. To introduce the abstract notion of a stream 3. To introduce the java File, Input/OutputStream,
More informationStream Manipulation. Lecture 11
Stream Manipulation Lecture 11 Streams and I/O basic classes for file IO FileInputStream, for reading from a file FileOutputStream, for writing to a file Example: Open a file "myfile.txt" for reading FileInputStream
More informationData stored in variables and arrays is temporary
Data stored in variables and arrays is temporary It s lost when a local variable goes out of scope or when the program terminates For long-term retention of data, computers use files. Computers store files
More informationJOSE LUIS JUAREZ VIVEROS com) has a. non-transferable license to use this Student Guide
Module 10 I/O Fundamentals Objectives Upon completion of this module, you should be able to: Write a program that uses command-line arguments and system properties Examine the Properties class Construct
More informationExceptions and Working with Files
Exceptions and Working with Files Creating your own Exceptions. You have a Party class that creates parties. It contains two fields, the name of the host and the number of guests. But you don t want to
More informationFundamental Java Syntax Summary Sheet for CISC101, Spring Java is Case - Sensitive!
Fundamental Java Syntax Summary Sheet for CISC101, Spring 2006 Notes: Items in italics are things that you must supply, either a variable name, literal value, or expression. Variable Naming Rules Java
More informationLecture 2. Two-Dimensional Arrays
Lecture 2 Two-Dimensional Arrays 1 Lecture Content 1. 2-D Array Basics 2. Basic Operations on 2-D Array 3. Storing Matrices with Special Properties 4. Applications of 2-D Array 2 1. 2-D Array Basics An
More informationHST 952. Computing for Biomedical Scientists Lecture 8
Harvard-MIT Division of Health Sciences and Technology HST.952: Computing for Biomedical Scientists HST 952 Computing for Biomedical Scientists Lecture 8 Outline Vectors Streams, Input, and Output in Java
More informationObject-Oriented Programming Design. Topic : Streams and Files
Electrical and Computer Engineering Object-Oriented Topic : Streams and Files Maj Joel Young Joel Young@afit.edu. 18-Sep-03 Maj Joel Young Java Input/Output Java implements input/output in terms of streams
More informationCPS122 Lecture: Input-Output
CPS122 Lecture: Input-Output Objectives: Last Revised April 3, 2017 1. To discuss IO to System.in/out/err 2. To introduce the abstract notion of a stream 3. To introduce the java File, Input/OutputStream,
More information1.00 Lecture 30. Sending information to a Java program
1.00 Lecture 30 Input/Output Introduction to Streams Reading for next time: Big Java 15.5-15.7 Sending information to a Java program So far: use a GUI limited to specific interaction with user sometimes
More informationActive Learning: Streams
Lecture 29 Active Learning: Streams The Logger Application 2 1 Goals Using the framework of the Logger application, we are going to explore three ways to read and write data using Java streams: 1. as text
More information5/29/2006. Announcements. Last Time. Today. Text File I/O Sample Programs. The File Class. Without using FileReader. Reviewed method overloading.
Last Time Reviewed method overloading. A few useful Java classes: Other handy System class methods Wrapper classes String class StringTokenizer class Assn 3 posted. Announcements Final on June 14 or 15?
More information12% of course grade. CSCI 201L Final - Written Fall /7
12% of course grade 1. Interfaces and Inheritance Does the following code compile? If so, what is the output? If not, why not? Explain your answer. (1.5%) interface I2 { public void meth1(); interface
More informationChapter 4 Java I/O. X i a n g Z h a n g j a v a c o s q q. c o m
Chapter 4 Java I/O X i a n g Z h a n g j a v a c o s e @ q q. c o m Content 2 Java I/O Introduction File and Directory Byte-stream and Character-stream Bridge between b-s and c-s Random Access File Standard
More informationChapter 10. IO Streams
Chapter 10 IO Streams Java I/O The Basics Java I/O is based around the concept of a stream Ordered sequence of information (bytes) coming from a source, or going to a sink Simplest stream reads/writes
More informationFile. Long term storage of large amounts of data Persistent data exists after termination of program Files stored on secondary storage devices
Java I/O File Long term storage of large amounts of data Persistent data exists after termination of program Files stored on secondary storage devices Magnetic disks Optical disks Magnetic tapes Sequential
More informationFile IO. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 20
File IO Computer Science and Engineering College of Engineering The Ohio State University Lecture 20 I/O Package Overview Package java.io Core concept: streams Ordered sequences of data that have a source
More informationC17: I/O Streams and File I/O
CISC 3120 C17: I/O Streams and File I/O Hui Chen Department of Computer & Information Science CUNY Brooklyn College 4/9/2018 CUNY Brooklyn College 1 Outline Recap and issues Review your progress Assignments:
More informationI/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O
I/O 10-7-2013 I/O in Java I/O streams vs. Reader/Writer HW#3 due today Reading Assignment: Java tutorial on Basic I/O public class Swimmer implements Cloneable { public Date geteventdate() { return (Date)
More informationJAVA NOTES DATA STRUCTURES AND ALGORITHMS
179 JAVA NOTES DATA STRUCTURES AND ALGORITHMS Terry Marris August 2001 19 RANDOM ACCESS FILES 19.1 LEARNING OUTCOMES By the end of this lesson the student should be able to picture a random access file
More informationIntermediate Programming. Streams
Intermediate Programming Lecture 9 File I/O Streams A stream is an object that allows for the flow of data between a program and some I/O device (or a file). If the flow is into a program it s an input
More informationCMPSCI 187: Programming With Data Structures. Lecture #24: Files and a Case Study David Mix Barrington 2 November 2012
CMPSCI 187: Programming With Data Structures Lecture #24: Files and a Case Study David Mix Barrington 2 November 2012 Files and a Case Study Volatile and Non-Volatile Storage Storing and Retrieving Objects
More informationFile I/O Introduction to File I/O Text Files The File Class Binary Files 614
10.1 Introduction to File I/O 574 Streams 575 Text Files and Binary Files 575 10.2 Text Files 576 Writing to a Text File 576 Appending to a Text File 583 Reading from a Text File 586 Reading a Text File
More informationTitle Description Participants Textbook
Podcast Ch23c Title: Binary Files Description: Overview of binary files; DataInputStream; DataOutputStream; Program 23.1; file compression Participants: Barry Kurtz (instructor); John Helfert and Tobie
More informationObjec&ves. Review. Standard Error Streams
Objec&ves Standard Error Streams Ø Byte Streams Ø Text Streams Oct 5, 2016 Sprenkle - CSCI209 1 Review What are benefits of excep&ons What principle of Java do files break if we re not careful? What class
More informationMany Stream Classes. File I/O - Chapter 10. Writing Text Files. Text Files vs Binary Files. Reading Text Files. EOF with hasmoreelements()
File I/O - Chapter 10 Many Stream Classes A Java is a sequence of bytes. An InputStream can read from a file the console (System.in) a network socket an array of bytes in memory a StringBuffer a pipe,
More informationSpecial error return Constructors do not have a return value What if method uses the full range of the return type?
23 Error Handling Exit program (System.exit()) usually a bad idea Output an error message does not help to recover from the error Special error return Constructors do not have a return value What if method
More information1.00 Lecture 31. Streams 2. Reading for next time: Big Java , The 3 Flavors of Streams
1.00 Lecture 31 Streams 2 Reading for next time: Big Java 18.6-18.8, 20.1-20.4 The 3 Flavors of Streams In Java, you can read and write data to a file: as text using FileReader and FileWriter as binary
More informationWhen we reach the line "z = x / y" the program crashes with the message:
CSCE A201 Introduction to Exceptions and File I/O An exception is an abnormal condition that occurs during the execution of a program. For example, divisions by zero, accessing an invalid array index,
More informationExample: Copying the contents of a file
Administrivia Assignment #4 is due imminently Due Thursday April 8, 10:00pm no late assignments will be accepted Sign up in the front office for a demo time Dining Philosophers code is online www.cs.ubc.ca/~norm/211/2009w2/index.html
More informationAlgorithms. Produced by. Eamonn de Leastar
Algorithms Produced by Eamonn de Leastar (edeleastar@wit.ie) Streams http://www.oracle.com/technetwork/java/javase/tech/index.html Introduction ± An I/O Stream represents an input source or an output destination.
More informationJava file manipulations
Java file manipulations 1 Categories of Java errors We learn that there are three categories of Java errors : Syntax error Runtime error Logic error. A Syntax error (compiler error) arises because a rule
More informationChapter 10 Input Output Streams
Chapter 10 Input Output Streams ICT Academy of Tamil Nadu ELCOT Complex, 2-7 Developed Plots, Industrial Estate, Perungudi, Chennai 600 096. Website : www.ictact.in, Email : contact@ictact.in, Phone :
More informationCOMP1406 Tutorial 11
COMP1406 Tutorial 11 Objectives: To gain more practice handling Exceptions. To create your own Exceptions. To practice reading and writing binary files. To practice reading and writing text files. To practice
More informationJava Object Serialization Specification
Java Object Serialization Specification Object serialization in the Java system is the process of creating a serialized representation of objects or a graph of objects. Object values and types are serialized
More informationWOSO Source Code (Java)
WOSO 2017 - Source Code (Java) Q 1 - Which of the following is false about String? A. String is immutable. B. String can be created using new operator. C. String is a primary data type. D. None of the
More informationObject-Oriented Programming in the Java language
Object-Oriented Programming in the Java language Part 5. Exceptions. I/O in Java Yevhen Berkunskyi, NUoS eugeny.berkunsky@gmail.com http://www.berkut.mk.ua Exceptions Exceptions in Java are objects. All
More informationC17a: Exception and Text File I/O
CISC 3115 TY3 C17a: Exception and Text File I/O Hui Chen Department of Computer & Information Science CUNY Brooklyn College 10/11/2018 CUNY Brooklyn College 1 Outline Discussed Error and error handling
More informationDistributed Programming in Java
Distributed Programming in Java Networking (1) Motivating Scenario apps apps apps apps 2/28 apps nslookup A program for looking up IP addresses 3/28 1 InetAddress This class represents an IP address Each
More informationJava Programming Unit 9. Serializa3on. Basic Networking.
Java Programming Unit 9 Serializa3on. Basic Networking. Serializa3on as per Wikipedia Serializa3on is the process of conver3ng a data structure or an object into a sequence of bits to store it in a file
More informationCompile error. 2. A run time error occurs when the program runs and is caused by a number of reasons, such as dividing by zero.
(טיפול בשגיאות) Exception handling We learn that there are three categories of errors : Syntax error, Runtime error and Logic error. A Syntax error (compiler error) arises because a rule of the language
More informationChapter 12. File Input and Output. CS 180 Sunil Prabhakar Department of Computer Science Purdue University
Chapter 12 File Input and Output CS 180 Sunil Prabhakar Department of Computer Science Purdue University Persistent Data Suppose we write a Bank application. How do we remember the account balances? What
More informationF1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept
F1 A Java program Ch 1 in PPIJ Introduction to the course The computer and its workings The algorithm concept The structure of a Java program Classes and methods Variables Program statements Comments Naming
More informationAnnouncement EXAM 2. Assignment 6 due Wednesday WEDNESDAY 7: :00 PM EE 129
Announcement EXAM 2 WEDNESDAY 7:00 -- 8:00 PM EE 129 Assignment 6 due Wednesday 1 Chapter 12 File Input and Output CS 180 Sunil Prabhakar Department of Computer Science Purdue University Persistent Data
More informationAdvanced Programming Methods. Seminar 12
Advanced Programming Methods Seminar 12 1. instanceof operator 2. Java Serialization Overview 3. Discuss how we can serialize our ToyLanguage interpreter. Please discuss the implementation of different
More information09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output.
CSE 143 Java Streams Reading: 19.1, Appendix A.2 GREAT IDEAS IN COMPUTER SCIENCE REPRESENTATION VS. RENDERING 4/28/2002 (c) University of Washington 09-1 4/28/2002 (c) University of Washington 09-2 Topics
More informationFile Operations in Java. File handling in java enables to read data from and write data to files
Description Java Basics File Operations in Java File handling in java enables to read data from and write data to files along with other file manipulation tasks. File operations are present in java.io
More informationCSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O
CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O 1 Sending Output to a (Text) File import java.util.scanner; import java.io.*; public class TextFileOutputDemo1 public static void
More informationCSCI 200 Lab 2 Inheritance, Polymorphism & Data Streams
CSCI 200 Lab 2 Inheritance, Polymorphism & Data Streams In this lab you will write a set of simple Java interfaces and classes that use inheritance and polymorphism. You will also write code that uses
More informationINFO1113. Calum Baird. October 5, Stuff Always check null Inline declare array Switch statement...
INFO1113 Calum Baird October 5, 2018 INFO1113 Notes Contents 1 Stuff 3 1.1 Always check null........................... 3 1.2 Inline declare array.......................... 3 1.2.1 Switch statement.......................
More informationFundamental Java Syntax Summary Sheet for CISC124, Fall Java is Case - Sensitive!
Fundamental Java Syntax Summary Sheet for CISC124, Fall 2015 Notes: Items in italics are things that you must supply, either a variable name, literal value, or expression. Java is Case - Sensitive! Variable
More informationJava Input/Output Streams
Java Input/Output Streams Rui Moreira Some useful links: http://java.sun.com/docs/books/tutorial/essential/toc.html#io Input Stream Output Stream Rui Moreira 2 1 JVM creates the streams n System.in (type
More informationFile class in Java. Scanner reminder. File methods 10/28/14. File Input and Output (Savitch, Chapter 10)
File class in Java File Input and Output (Savitch, Chapter 10) TOPICS File Input Exception Handling File Output Programmers refer to input/output as "I/O". Input is received from the keyboard, mouse, files.
More informationLARA TECHNOLOGIES EXAM_SPECIALSIX SECTION-1
Q: 01. SECTION-1 Q: 02 Given: 12. import java.io.*; 13. public class Forest implements Serializable { 14. private Tree tree = new Tree(); 15. public static void main(string [] args) { 16. Forest f = new
More informationFiles and IO, Streams. JAVA Standard Edition
Files and IO, Streams JAVA Standard Edition Java - Files and I/O The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent
More informationAny serious Java programmers should use the APIs to develop Java programs Best practices of using APIs
Ananda Gunawardena Java APIs Think Java API (Application Programming Interface) as a super dictionary of the Java language. It has a list of all Java packages, classes, and interfaces; along with all of
More informationData Structures and Algorithms
Data Structures and Algorithms Introduction: Data Structures What is a data structure? Way of storing data in computer so can be used efficiently Set of operations that access the data in prescribed ways
More informationI pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.
Name: Covers Chapters 1-3 50 mins CSCI 1301 Introduction to Programming Armstrong Atlantic State University Instructor: Dr. Y. Daniel Liang I pledge by honor that I will not discuss this exam with anyone
More informationVoyager Interoperability Guide Version 1.1 for Voyager 8.0
Voyager Interoperability Guide Version 1.1 for Voyager 8.0 Table of Contents Introduction... 3 Audience... 3 Prerequisites... 3 Overview... 3 Contacting Technical Support... 3 The Distributed Data Model...
More informationCertification In Java Language Course Course Content
Introduction Of Java * What Is Java? * How To Get Java * A First Java Program * Compiling And Interpreting Applications * The JDK Directory Structure Certification In Java Language Course Course Content
More informationFinal Exam. CSC 121 Fall Lecturer: Howard Rosenthal. Dec. 13, 2017
Your Name: Final Exam. CSC 121 Fall 2017 Lecturer: Howard Rosenthal Dec. 13, 2017 The following questions (or parts of questions) in numbers 1-17 are all worth 2 points each. The programs have indicated
More informationJava Identifiers, Data Types & Variables
Java Identifiers, Data Types & Variables 1. Java Identifiers: Identifiers are name given to a class, variable or a method. public class TestingShastra { //TestingShastra is an identifier for class char
More informationC17: File I/O and Exception Handling
CISC 3120 C17: File I/O and Exception Handling Hui Chen Department of Computer & Information Science CUNY Brooklyn College 10/24/2017 CUNY Brooklyn College 1 Outline Recap and issues Exception Handling
More informationProgramming with Java
Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules
More information