Simple Java Input/Output

Similar documents
Simple Java I/O. Part I General Principles

PIC 20A Streams and I/O

HST 952. Computing for Biomedical Scientists Lecture 8

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

CS 251 Intermediate Programming Java I/O Streams

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

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

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

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

Java Input/Output. 11 April 2013 OSU CSE 1

Lecture 11.1 I/O Streams

Programming Languages and Techniques (CIS120)

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

IT101. File Input and Output

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

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

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

Objec&ves. Review. Standard Error Streams

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

Introduction Unit 4: Input, output and exceptions

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

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

COMP-202: Foundations of Programming. Lecture 12: Linked List, and File I/O Sandeep Manjanna, Summer 2015

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

1.00 Lecture 30. Sending information to a Java program

Streams and File I/O

COMP-202: Foundations of Programming. Lecture 22: File I/O Jackie Cheung, Winter 2015

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

Dining philosophers (cont)

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

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

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

File I/O Introduction to File I/O Text Files The File Class Binary Files 614

Text User Interfaces. Keyboard IO plus

CS Programming I: File Input / Output

Darshan Institute of Engineering & Technology for Diploma Studies

Lab 2: File Input and Output

Streams and File I/O

Exceptions and Working with Files

CS Programming I: File Input / Output

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

Programming Languages and Techniques (CIS120)

BASIC INPUT/OUTPUT. Fundamentals of Computer Science

Programming Languages and Techniques (CIS120)

Object-Oriented Programming Design. Topic : Streams and Files

Sri Vidya College of Engineering & Technology Question Bank

Programming Languages and Techniques (CIS120)

5/29/2006. Announcements. Last Time. Today. Text File I/O Sample Programs. The File Class. Without using FileReader. Reviewed method overloading.

Project 1. Java Data types and input/output 1/17/2014. Primitive data types (2) Primitive data types in Java

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

Software Practice 1 - File I/O

Experiment No: Group B_4

Starting Out with Java: From Control Structures Through Objects Sixth Edition

ITI Introduction to Computer Science II

COMP200 INPUT/OUTPUT. OOP using Java, based on slides by Shayan Javed

CSC 1214: Object-Oriented Programming

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

I/O STREAM (REQUIRED IN THE FINAL)

Input from Files. Buffered Reader

Programming Languages and Techniques (CIS120)

Data Structures. 03 Streams & File I/O

Full file at

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

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

Streams and File I/O

Welcome to CIS 068! 1. GUIs: JAVA Swing 2. (Streams and Files we ll not cover this in this semester, just a review) CIS 068

Performing input and output operations using a Byte Stream

Input-Output and Exception Handling

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

Objec-ves JAR FILES. Jar files. Excep-ons. Files Streams. Ø Wrap up Ø Why Excep-ons? 9/30/16. Oct 3, 2016 Sprenkle - CSCI209 1

Any serious Java programmers should use the APIs to develop Java programs Best practices of using APIs

Internet Technology 2/7/2013

Unit 10: exception handling and file I/O

Object-Oriented Programming in Java

Variables of class Type. Week 8. Variables of class Type, Cont. A simple class:

Lab 10: Sockets 12:00 PM, Apr 4, 2018

Object Oriented Design with UML and Java. PART VIII: Java IO

I/O Streams. COMP 202 File Access. Standard I/O. I/O Stream Categories

COMP 202 File Access. CONTENTS: I/O streams Reading and writing text files. COMP File Access 1

C17: I/O Streams and File I/O

Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently.

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

Streams and File I/O

File I/O Array Basics For-each loop

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

Full file at

Java Console Input/Output The Basics

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

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

Lesson 3: Accepting User Input and Using Different Methods for Output

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

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

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

Principles of Computer Science I

Computer Science is...

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

CS193j, Stanford Handout #26. Files and Streams

COMP 202 File Access. CONTENTS: I/O streams Reading and writing text files. COMP 202 File Access 1

Transcription:

Simple Java Input/Output

Prologue They say you can hold seven plus or minus two pieces of information in your mind. I can t remember how to open files in Java. I ve written chapters on it. I ve done it a bunch of times, but it s too many steps. And when I actually analyze it, I realize these are just silly design decisions that they made. Even if they insisted on using the Decorator pattern in java.io, they should have had a convenience constructor for opening files simply. Because we open files all the time, but nobody can remember how. It is too much information to hold in your mind. Bruce Eckel, http://www.artima.com/intv/aboutme2.html

Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for data (sometimes both) An input stream may be associated with the keyboard An input stream or an output stream may be associated with a file Different streams have different characteristics: A file has a definite length, and therefore an end Keyboard input has no specific end

How to do I/O import java.io.*; Open the stream Use the stream (read, write, or both) Close the stream

Why Java I/O is hard Java I/O is very powerful, with an overwhelming number of options Any given kind of I/O is not particularly difficult The trick is to find your way through the maze of possibilities

Opening a stream There is data external to your program that you want to get, or you want to put data somewhere outside your program When you open a stream, you are making a connection to that external place Once the connection is made, you forget about the external place and just use the stream

Example of opening a stream A FileReader is a used to connect to a file that will be used for input: FileReader filereader = new FileReader(fileName); The filename specifies where the (external) file is to be found You never use filename again; instead, you use filereader

Using a stream Some streams can be used only for input, others only for output, still others for both Using a stream means doing input from it or output to it Example int charasint = filereader.read( ); The filereader.read() method reads one character and returns it as an integer, or -1 if there are no more characters to read The meaning of the integer depends on the file encoding (ASCII, Unicode, other) You can cast from int to char: char ch = (char)filereader.read( );

Manipulating the input data Reading characters as integers isn t usually what you want to do A BufferedReader will convert integers to characters; it can also read whole lines The constructor for BufferedReader takes a FileReader parameter: BufferedReader bufferedreader = new BufferedReader(fileReader); To read a line with a BufferedReader: String s = bufferedreader.readline( ); A BufferedReader will return null if there is nothing more to read

Closing A stream is an expensive resource There is a limit on the number of streams that you can have open at one time You should not have more than one stream open on the same file You must close a stream before you can open it again Always close your streams! Java will normally close your streams for you when your program ends, but it isn t good style to depend on this

Text files Text (.txt) files are the simplest kind of files Text files can be used by many different programs Formatted text files (such as.doc files) also contain binary formatting information Only programs that know the secret code can make sense of formatted text files To other programs, such files are just unintelligible binary information Compilers, in general, work only with text Comma-separated value (.csv) files are also easy to work with

Putting it all together 1. Create a FileReader Need to catch a FileNotFoundException 2. Create a BufferedReader 3. Read your file line by line using the BufferedReader Need to catch an IOException 4. Close the BufferedReader Eclipse example: BufferedReaderExample.java

How did I figure that out? I wanted to read lines from a file I thought there might be a suitable readsomething method, so I went to the API Index I found a readline method in several classes; the most promising was the BufferedReader class The constructor for BufferedReader takes a Reader as an argument Reader is an abstract class, but it has several implementations, including InputStreamReader FileReader is a subclass of InputStreamReader There is a constructor for FileReader that takes as its argument a (String) file name

Output streams Files are usually written to using an OutputStream Of course, it is once again an abstract class A useful subclass of OutputStream is FileOutputStream System.out is actually a PrintStream, which is also a subclass of OutputStream Syntax FileOutputStream fos = new FileOutputStream(filename, append); If append is true, you will append to the end of the file Of course, a is FileOutputStream not really useful (but there are exceptions ) because it only writes a byte/int at a time

Enter the PrintWriter The class that is actually useful when writing to a file is a PrintWriter A PrintWriter takes a FileOutputStream as input Syntax PrintWriter pw = new PrintWriter(fos); With a PrintWriter, you can write strings or entire lines to file The most useful functions are print and println which work exactly like System.out.print and System.out.println

Flushing the buffer When you put information into a buffered output stream, it goes into a buffer The buffer may or may not be written out right away If your program crashes, you may not know how far it got before it crashed Flushing the buffer forces the information to be written out Buffers are automatically flushed when the program ends normally Usually it is your responsibility to flush buffers if the program does not end normally The PrintWriter can do the flushing for you pw.flush()

Close your PrintWriter Like any other stream this needs to be closed, too Java will close it when your program ends but this is bad style If your program crashes, sometimes Java will get confused and won t close it properly, so make sure you always close it!

Putting it all together 1. Create a FileOutputStream Need to catch a FileNotFoundException 2. Create a PrintWriter 3. Write strings or lines using the PrintWriter 4. Close the PrintWriter Eclipse example: PrintWriterExample.java

The Scanner class Takes any InputStream as input to the constructor Could be a file Scanner scanner = new Scanner(new File(filename)); Could be System.in (the keyboard) Scanner scanner = new Scanner(System.in); Both throw FileNotFoundException You can even read from a String Scanner scanner = new Scanner(myString); This can useful for parsing a String

Several useful Scanner methods Check if there is more stuff to read Different methods depending on the type of input sc.nextboolean(), sc.nextbyte(), sc.nextshort(), sc.nextint(), sc.nextlong(), sc.nextfloat(), sc.nextdouble() You can read the whole remaining line We already saw the method nextline() Also reads the whole string until the user presses Enter You can also read token by token A token can be an int/string/whatever the Scanner was set up with Use the next() method for this Probably less useful than nextline()

Formatted output Java 5 has a printf method, similar to that of C System.out.printf(someString + formatcode, arguments); Each format code is a String of the form: % width code The width is the number of characters that are output (with blank fill) By default, output is right-justified A negative width means to left-justify the output Some values for the code are s for strings, d for integers, f for floating point numbers, b for booleans For floating point numbers, the width has the form total.right, where total is the total width and right is the number of digits to the right of the decimal point There are a huge number of options for formatting dates, which we won t cover Eclise example: PrintfClass.java