Software Practice 1 - File I/O

Similar documents
File IO. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 20

Darshan Institute of Engineering & Technology for Diploma Studies

I/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O

Software Practice 1 Basic Grammar

Byte and Character Streams. Reading and Writing Console input and output

Lecture 11.1 I/O Streams

PIC 20A Streams and I/O

Chapter 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

Input, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003

CSC 1214: Object-Oriented Programming

CS 251 Intermediate Programming Java I/O Streams

Object-Oriented Programming Design. Topic : Streams and Files

09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output.

Exceptions and Working with Files

Basic I/O - Stream. Java.io (stream based IO) Java.nio(Buffer and channel-based IO)

The I/O Package. THE Java platform includes a number of packages that are concerned with the CHAPTER20

File Processing in Java

Agenda & Reading. Python Vs Java. COMPSCI 230 S Software Construction

Each command-line argument is placed in the args array that is passed to the static main method as below :

COMP 213. Advanced Object-oriented Programming. Lecture 19. Input/Output

Java Input / Output. CSE 413, Autumn 2002 Programming Languages.

Objec&ves. Review. Standard Error Streams

输 入输出相关类图. DataInput. DataOutput. java.lang.object. FileInputStream. FilterInputStream. FilterInputStream. FileOutputStream

File Input/Output. Introduction to Computer Science I. Overview (1): Overview (2): CSE 1020 Summer Bill Kapralos. Bill Kapralos.

Simple Java Input/Output

CSB541 Network Programming 網路程式設計. Ch.2 Streams 吳俊興國立高雄大學資訊工程學系

CS 200 File Input and Output Jim Williams, PhD

Course Content. Objectives of Lecture 22 File Input/Output. Outline of Lecture 22. CMPUT 102: File Input/Output Dr. Osmar R.

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O

ITI Introduction to Computer Science II

File. Long term storage of large amounts of data Persistent data exists after termination of program Files stored on secondary storage devices

Software Practice 1 - Socket

תוכנה 1 תרגול 8 קלט/פלט רובי בוים ומתי שמרת

I/O Streams. Object-oriented programming

Lab 2: File Input and Output

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Au

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Sp

Programming Languages and Techniques (CIS120)

Software Practice 1 - OOP (1) Class and Method

Today. Book-keeping. File I/O. Subscribe to sipb-iap-java-students. Inner classes. Debugging tools

Experiment No: Group B_4

Overview CSE 143. Input and Output. Streams. Other Possible Kinds of Stream Converters. Stream after Stream... CSE143 Wi

Basic Java IO Decorator pattern Advanced Java IO. Java IO - part 2 BIU OOP. BIU OOP Java IO - part 2

Techniques of Java Programming: Streams in Java

Java Input/Output. 11 April 2013 OSU CSE 1

Chapter 10 Input Output Streams

JOSE LUIS JUAREZ VIVEROS com) has a. non-transferable license to use this Student Guide

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Objec&ves STANDARD ERROR. Standard Error Streams. Ø Byte Streams Ø Text Streams 10/5/16. Oct 5, 2016 Sprenkle - CSCI209 1

Chapter 10. IO Streams

1.00 Lecture 30. Sending information to a Java program

Software 1 with Java. Recitation No. 7 (Java IO) May 29,

Sri Vidya College of Engineering & Technology Question Bank

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.

Software Practice 1 - Error Handling

Software 1. Java I/O

Special error return Constructors do not have a return value What if method uses the full range of the return type?

Software Practice 1. Course Overview Lecture Schedule Today s Task Contact

Software 1 with Java. Recitation No. 9 (Java IO) December 10,

Principles of Software Construction: Objects, Design and Concurrency. Design Case Study: Stream I/O. toad

1993: renamed "Java"; use in a browser instead of a microwave : Sun sues Microsoft multiple times over Java

needs to be reliable, easy to change, retarget efficiency is secondary implemented as interpreter, with virtual machine

Software Practice 3 Today s lecture Today s Task

CPS122 Lecture: Input-Output

Internet Technology 2/7/2013

Object-Oriented Programming in the Java language

CPS122 Lecture: Input-Output

Software Practice 1 - Multithreading

I/O STREAM (REQUIRED IN THE FINAL)

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Lecture 4: Exceptions. I/O

HST 952. Computing for Biomedical Scientists Lecture 8

Java IO and C++ Streams

Chapter 10. File I/O. Copyright 2016 Pearson Inc. All rights reserved.

Jonathan Aldrich Charlie Garrod

Lab 5: Java IO 12:00 PM, Feb 21, 2018

Lecture 22. Java Input/Output (I/O) Streams. Dr. Martin O Connor CA166

Example: Copying the contents of a file

CS Week 11. Jim Williams, PhD

Performing input and output operations using a Byte Stream

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

7 Streams and files. Overview. Binary data vs text. Binary data vs text. Readers, writers, byte streams. input-output

Input from Files. Buffered Reader

CS112 Lecture: Streams

CS Programming I: File Input / Output

Programming Languages and Techniques (CIS120)

Remedial Java - io 8/09/16. (remedial) Java. I/O. Anastasia Bezerianos 1

CISC 323 (Week 9) Design of a Weather Program & Java File I/O

CS Programming I: File Input / Output

Stream Manipulation. Lecture 11

10.1 Overview 162 CHAPTER 10 CHARACTER STREAMS

I/O streams. Byte Streams Character Streams InputStream ByteArrayInputStream FileInputStream FilterInputStream

Streams and File I/O

Tirgul 1. Course Guidelines. Packages. Special requests. Inner classes. Inner classes - Example & Syntax

Files and IO, Streams. JAVA Standard Edition

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

Dining philosophers (cont)

Transcription:

Software Practice 1 - File I/O Stream I/O Buffered I/O File I/O with exceptions CSV format Practice#6 Prof. Joonwon Lee T.A. Jaehyun Song Jongseok Kim (42) T.A. Sujin Oh Junseong Lee 1 (43) / 38

2 / 38 Basic I/O in Java For printing System.out.println () System.err.println () For scanning from file?

3 / 38 Standard Streams A feature of many operating systems Read input from the keyboard and write output to the display Also support I/O on files and between programs But these two features are controlled by the command line interpreter, not program

4 / 38 Standard Streams in Java Standard input System.in object of InputStream with console in Standard output System.out object of PrintStream with console out PrintStream is inherited from OutputStream Standard error System.err object of PrintStream with console err

5 / 38 Read Data with System.in public class Main { public static void main (String[] args) { int data = System.in.read (); while (data!= -1) { char thechar = (char) data; data = System.in.read ();

6 / 38 Write Data with System.out public class Main { public static void main (String[] args) { int[] data = {1, 2, 3; System.out.println (data);

7 / 38 Write Data with System.err public class Main { public static void main (String[] args) { String errmsg = Example of System.err! ; System.err.println (data);

How about File I/O? Same with Standard Streams FileInputStream Stream for reading data from file FileOutputStream Stream for writing data from file FileErrorStream(?) File I/O does not have error I/O Usages are also same with Standard Streams! * https://docs.oracle.com/javase/7/docs/api/java/io/fileinputstream.html 8 / 38

FileInputStream Obtains input bytes from a file in a file system Reads streams of raw bytes such as image Inherited from class InputStream Also has same way to read data * https://docs.oracle.com/javase/7/docs/api/java/io/fileinputstream.html 9 / 38

10 / 38 Read Data with FileInputStream public class Main { public static void main (String[] args) { InputStream fis = new FileInputStream ( path ); int data = fis.read (); while (data!= -1) { char thechar = (char) data; data = fis.read (); fis.close ();

InputStreamReader A bridge from byte streams to character streams Reads bytes and decodes them into characters using a specified charset Generate reader of the given InputStream object Declared in java.io package Inherited from class java.io.reader Provides lock for reading data from single resource * https://docs.oracle.com/javase/7/docs/api/java/io/inputstreamreader.html 11 / 38

Constructor of Stream Reader InputStreamReader Constructor and Description InputStreamReader(InputStream in) Creates an InputStreamReader that uses the default charset. InputStreamReader(InputStream in, Charset cs) Creates an InputStreamReader that uses the given charset. InputStreamReader(InputStream in, CharsetDecoder dec) Creates an InputStreamReader that uses the given charset decoder. InputStreamReader(InputStream in, String charsetname) Creates an InputStreamReader that uses the named charset. * https://docs.oracle.com/javase/7/docs/api/java/io/inputstreamreader.html 12 / 38

Read Data with Stream Reader InputStreamReader Modifier and Type void String int int boolean Method and Description close() Closes the stream and releases any system resources a ssociated with it. getencoding() Returns the name of the character encoding being used by this stream. read() Reads a single character. read(char[] cbuf, int offset, int length) Reads characters into a portion of an array. ready() Tells whether this stream is ready to be read. * https://docs.oracle.com/javase/7/docs/api/java/io/inputstreamreader.html 13 / 38

14 / 38 Example of InputStreamReader public class Main { public static void main (String[] args) { Reader isr = new InputStreamReader (System.in); int data = isr.read (); String str = ; while (data!= -1) { str += (char) data; data = isr.read (); isr.close ();

15 / 38 Example of InputStreamReader public class Main { public static void main (String[] args) { InputStream fis = new FileInputStream ( path ); Reader isr = new InputStreamReader (fis); int data = isr.read (); String str = ; while (data!= -1) { str += (char) data; data = isr.read (); isr.close ();

BufferedReader Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines The buffer size may be specified, or the default size may be used The default size is large enough to most purposes * https://docs.oracle.com/javase/7/docs/api/java/io/bufferedreader.html 16 / 38

17 / 38 Example of BufferedReader public class Main { public static void main (String[] args) { InputStream fis = new FileInputStream ( path ); Reader isr = new InputStreamReader (fis); Reader br = new BufferedReader (isr); String data = br.readline (); br.close ();

FileOutputStream An output stream for writing data to a File or to a FileDescriptor Whether or not a file is available or may be created depends upon the underlying platform Inherited from class OutputStream Also has same way to write data * https://docs.oracle.com/javase/7/docs/api/java/io/fileinputstream.html 18 / 38

19 / 38 Write Data with FileOutputStream public class Main { public static void main (String[] args) { OutputStream fos = new FileOutputStream ( path ); byte[] data = { a, b, c ; fos.write (data); fos.write (data[0]); fos.flush (); fos.close ();

OutputStreamWriter A bridge from character streams to byte streams Characters written to it are encoded into bytes using a specified charset Generate writer of the given OutputStream object Declared in java.io package Inherited from class java.io.writer Provides lock for writing data to single resource Highly recommend to use BufferedWriter! * https://docs.oracle.com/javase/7/docs/api/java/io/outputstreamwriter.html 20 / 38

Constructor of Stream Writer OutputStreamWriter Constructor and Description OutputStreamWriter(OutputStream out) Creates an OutputStreamWriter that uses the default character encoding. OutputStreamWriter(OutputStream out, Charset cs) Creates an OutputStreamWriter that uses the given charset. OutputStreamWriter(OutputStream out, CharsetEncoder enc) Creates an OutputStreamWriter that uses the given charset encoder. OutputStreamWriter(OutputStream out, String charsetname) Creates an OutputStreamWriter that uses the named charset. * https://docs.oracle.com/javase/7/docs/api/java/io/outputstreamwriter.html 21 / 38

Write Data with Stream Writer OutputStreamWriter Modifier and Type Method and Description void void String void close() Closes the stream, flushing it first. flush() Flushes the stream. getencoding() Returns the name of the character encoding being used b y this stream. write(char[] cbuf, int off, int len) Writes a portion of an array of characters. void write(int c) Writes a single character. void write(string str, int off, int len) Writes a portion of a string. * https://docs.oracle.com/javase/7/docs/api/java/io/outputstreamwriter.html 22 / 38

23 / 38 Example of OutputStreamWriter public class Main { public static void main (String[] args) { Writer osw = new OutputStreamWriter (System.out); String data = abc ; osw.write (data, 0, 3); osw.write (data, 0, 1); osw.flush (); osw.close ();

24 / 38 Example of OutputStreamWriter public class Main { public static void main (String[] args) { OutputStream fos = new FileOutputStream ( path ); Writer osw = new OutputStreamWriter (fos); String data = abc ; osw.write (data, 0, 3); osw.write (data, 0, 1); osw.flush (); osw.close ();

BufferedWriter Writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings The buffer size may be specified, or the default size may be used The default size is large enough to most purposes * https://docs.oracle.com/javase/7/docs/api/java/io/bufferedreader.html 25 / 38

26 / 38 Example of BufferedWriter public class Main { public static void main (String[] args) { OutputStream fos = new FileOutputStream ( path ); Writer osw = new OutputStreamWriter (fos); Writer bw = new BufferedWriter (osw); String data = abc ; bw.write (data, 0, 3); bw.write (data, 0, 1); bw.flush (); bw.close ();

27 / 38 File does not exist! If file not exists, reader (and some cases writer also) cannot do anything When program tries to access the file, error will occur Preparing for this error, we have to handle the exception with try-catch!

28 / 38 File Related Exceptions IOException Signals that an I/O exception of some sort has occurred This class is the general class of exceptions produced by failed or interrupted I/O operations FileNotFoundException Signals that an attempt to open the file denoted by a specified pathname has failed

BufferedReader with exception public class Main { public static void main (String[] args) { Reader isr, br; InputStream fis; try { fis = new FileInputStream ( path ); isr = new InputStreamReader (fis); br = new BufferedReader (isr); String data = br.readline (); catch (FileNotFoundException IOException e) { e.printstacetrace (); finally { br.close (); 29 / 38

BufferedWriter with exception public class Main { public static void main (String[] args) { Writer osw, bw; OutputStream fos; try { fos = new FileOutputStream ( path ); osw = new OutputStreamWriter (fos); bw = new BufferedWriter (osw); String data = abc ; osw.write (data, 0, 3); osw.write (data, 0, 1); catch (IOException e) { e.printstacktrace (); finally { bw.close (); 30 / 38

31 / 38 CSV format Comma-separated values file stores tabular data in plain text Each line of the file is a data record Each record consists of one or more fields, separated by commas The use of the comma as a field separator is the source of the name for the file format

32 / 38 Example of CSV format Biochemical Oxygen Demand "","Time","demand" "1",1,8.3 "2",2,10.3 "3",3,19 "4",4,16 "5",5,15.6 "6",7,19.8

33 / 38 Example of CSV format Student Admissions at UC Berkeley "","Admit","Gender","Dept","Freq" "1","Admitted","Male","A",512 "2","Rejected","Male","A",313 "3","Admitted","Female","A",89 "4","Rejected","Female","A",19

34 / 38 Example of CSV format Matrix Representation 1,2,3,4,5 2,3,4,5,6 3,4,5,6,7

35 / 38 How to read them? Optionally if the file contains the label, read them first in the outside of loop body Read the contents in the loop body with readline method of BufferedReader class Handle the I/O related exceptions for missed contents reading or etc. https://www.mkyong.com/java/how-to-read-and-parse-csv-file-in-java/

36 / 38 [Lab Practice #6] Read CSV file without any errors Calculate the multiplication of two matrices Implement 3 classes CSVMatrixReader CSVMatrixWriter CSVMatrixCalculator

37 / 38 [Lab Practice #6] Read number from CSV input file All value is large or equal to 0 Matrix number has float type Write only dot(.) or number to output file

[Submit] Upload to i-campus Compress your 3 java files to zip file CSVMatrixReader.java CSVMatrixWriter.java CSVMatrixCalculator.java Do not use any package keyword File name: studentid_lab06.zip Due date Today 23:59:59 Class 42 (04/16 Monday) Class 43 (04/18 Wednesday) Penalty: -10% of each lab score per one day 38 / 38