+ All Categories
Home > Documents > Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong...

Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong...

Date post: 14-Sep-2020
Category:
Upload: others
View: 3 times
Download: 0 times
Share this document with a friend
27
Copyright, 2013 © Multimedia Lab., Java Basic I/O Seong Jong Choi [email protected] Multimedia Lab. Dept. of Electrical and Computer Eng. University of Seoul Seoul, Korea http://www.mmlab.net
Transcript
Page 1: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

Copyright, 2013 © Multimedia Lab.,

Java Basic I/O

Seong Jong [email protected]

Multimedia Lab.Dept. of Electrical and Computer Eng.University of SeoulSeoul, Koreahttp://www.mmlab.net

Page 2: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

I/O Stream

• A stream is a “sequence of data”, i.e. one item at a

time.

2019-06-12 Seong Jong Choi Java Basic Concepts-2

Page 3: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

I/O Stream Type

Stream type

Byte Streams handle I/O of raw binary data.

Character Streams

handle I/O of Unicode character data,

automatically handling translation to and from

the local character set.

Buffered Streams optimize input and output by reducing the

number of calls to the native API.

Data Streams handle binary I/O of primitive data type and

String values.

Object Streams handle binary I/O of objects.

2019-06-12 Seong Jong Choi Java Basic Concepts-3

Page 4: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

Operation Chain Stream Connection Stream

Writing

Text Files

Reading

Text Files

Writing

Binary Files

Reading

Binary Files

File I/O: Stream Class Chaining

2019-06-12 Seong Jong Choi Java Basic Concepts-4

FileOutputStreamDataOutputStream BufferedOutputStream

ObjectOutputStream

FileInputStreamBufferedInputStreamDataInputStream

ObjectInputStream

FileWriter

PrintWriterBufferedWriter

FileReaderBufferedReader

JavaProgram Disk

File

Page 5: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

파일 외의 입출력

2019-06-12 Seong Jong Choi Java Basic IO-5

InputStream(System.in)InputStreamReaderBufferedReader

SocketInputStreamReaderBufferedReader

SocketPrintWriter

Page 6: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

I/O Class Hierarchy

• The dotted clouds are abstract classes.

• Byte-oriented streams

– Intended for general-purpose input and output.

– Data may be primitive data types or raw bytes.

• Character-oriented streams

– Intended for character data.

– Data is transformed from/to 16 bit Java char used inside programs to the UTF format used externally

2019-06-12 Seong Jong Choi Java Basic Concepts-6

Page 7: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

I/O Stream Class

Stream type Related Class

Byte Streams

(Connection)

General I/O: InputStream/OutputStream

File I/O: FileInputStream/FileOutputStream

Character Streams

(Connection)

General I/O: Reader/Writer

File I/O: FileReader/FileWriter

Buffered Streams

(chain)

Byte streams: BufferedInputStream/BufferedOutputStream

Character streams: BufferedReader/BufferedWriter

Data Streams

(Chain)DataInputStream/DataOutputStream

Object Streams

(Chain)ObjectInputStream/ObjectOutputStream

Formatting

(Chain)

Byte Stream: PrintStream (for System.out and System.err)

Character Stream: PrintWriter2019-06-12 Seong Jong Choi Java Basic Concepts-7

Page 8: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

Stream Chaining

• Connection Streams– Represents Connection to a source or destination (file, sockets, etc.)

• Chain streams– Can’t connect on their own and must be chained to a connection stream.

• Decoration Design Pattern

2019-06-12 Seong Jong Choi Java Basic Concepts-8

Page 9: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

2019-06-12 Seong Jong Choi Java Basic Concepts-9

Page 10: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

Processing (chain) Streams, Example 2

• A processing stream operates on the data supplied by another stream. Often a processing stream acts as a buffer for the data coming from another stream. A buffer is a block of main memory used as a work area. For example, disks usually deliver data in blocks of 512 bytes, no matter how few bytes a program has asked for. Usually the blocks of data are buffered and delivered from the buffer to the program in the amount the program asked for.

• A program can set all this up by declaring a BufferedReader as follows:

• BufferedReader stdin =

new BufferedReader(

new InputStreamReader( System.in ) );

2019-06-12 Seong Jong Choi Java Basic Concepts-10

Page 11: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

Byte Streams

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

public class CopyBytes {

public static void main(String[] args) throws IOException {

FileInputStream in = null;

FileOutputStream out = null;

try {

in = new FileInputStream("xanadu.txt");

out = new FileOutputStream("outagain.txt");

int c;

while ((c = in.read()) != -1) {

out.write(c);

}

} finally {

if (in != null) {

in.close();

}

if (out != null) {

out.close();

}

}

}

}

2019-06-12 Seong Jong Choi Java Basic Concepts-11

Page 12: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

InputStream

• InputStream is an abstract class from which all byte-oriented input streams are derived. Its descendant classes are used for general-purpose input (non-character input). These streams deliver data to a program in groups of 8-bit bytes. The bytes can be grouped into the size necessary for the type of data.

• For example, if a disk file contains 32-bit int data, data can be delivered to the program in 4-byte groups in the same format as Java primitive type int.

• We will be mostly concerned with DataInputStream and FileInputStream.

2019-06-12 Seong Jong Choi Java Basic Concepts-12

Page 13: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

OutputStream

• OutputStream is an abstract class from which all byte-oriented output streams are derived. Its descendant classes are used for general-purpose (non-character output). These streams are aimed at writing groups of 8-bit bytes to output destinations. The bytes are in the same format as Java primitive types. For example, 4-byte groups corresponding to type int can be written to a disk file.

• We will mostly be interested in FileOutputStream and DataOutputStream. We have used PrintStream many times already, because System.out is an object of that type.

2019-06-12 Seong Jong Choi Java Basic Concepts-13

Page 14: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

Character Streams: Example

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

public class CopyCharacters {

public static void main(String[] args) throws IOException {

FileReader inputStream = null;

FileWriter outputStream = null;

try {

inputStream = new FileReader("xanadu.txt");

outputStream = new FileWriter("characteroutput.txt");

int c;

while ((c = inputStream.read()) != -1) {

outputStream.write(c);

}

} finally {

if (inputStream != null) {

inputStream.close();

}

if (outputStream != null) {

outputStream.close();

}

}

}

}

2019-06-12 Seong Jong Choi Java Basic Concepts-14

Page 15: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

Character Streams

• Readers and Writers deal with character streams.

These are abstract classes. A program must use

classes derived from them. For example, a

BufferedReader is a Reader.

• Character streams are optimized for handling

character data. They also translate between the

internal format used by Java programs and an

external format used for text files. Inside a Java

program character data is represented with the

16-bit char data type. The characters of a String

also use this 16-bit code. On a disk file,

characters are represented in a format called

UTF. This format uses one to four bytes per

character and is intended to be a universal

format—one format for all text files in any

language anywhere in the world.

2019-06-12 Seong Jong Choi Java Basic Concepts-15

Page 16: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

Character Write: Writer

• Writer is an abstract class from which all character-oriented output streams are derived. All these streams are aimed at receiving 16-bit char data from a program, and sending it to another destination, which may use a different character format (such as UTF format on a disk file).

• All these classes are character-oriented output streams. We will be especially interested in FileWriter and PrintWriterclasses.

• PrintWriter provides line printing for both MS Windows(\r\n) and Unix(\n), and requires no exception handling.

2019-06-12 Seong Jong Choi Java Basic Concepts-16

Page 17: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

Character Write: All-in-one

2019-06-12 Seong Jong Choi Java Basic IO-17

FileWriter

PrintWriterBufferedWriter

JavaProgram Disk

File

//http://chortle.ccsu.edu/java5/Notes/chap83/ch83_17.html

import java.io.*;

import java.util.Scanner;

class PowerTable{

public static void main ( String[] args ) {

// Get filename and create the file

PrintWriter printer = null;

Scanner scan = new Scanner( System.in );

String fileName = "";

System.out.print("Enter Filename-->");

try {

fileName = scan.next();

// create the PrintWriter and enable automatic flushing

printer = new PrintWriter( new BufferedWriter( new FileWriter( fileName )), true );

}

catch ( IOException iox ) {

System.out.println("Error in creating file");

return;

}

// Write out the table.

//No Exception handling!!!!

int value = 1;

printer.println( "Power\tValue" );

for ( int pow=0; pow<=20; pow++ ) {

printer.print ( pow );

printer.print ( '\t' );

printer.println( value );

value = value*2;

}

printer.close();

}

}

Page 18: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

FileWriter

2019-06-12 Seong Jong Choi Java Basic IO-18

FileWriter

PrintWriterBufferedWriter

JavaProgram Disk

File

주기능

– 내부 16-bit char를 UTF로변환하여파일에저장한다.

Constructors– FileWriter(String fileName) : An IOException is thrown if the file cannot be created.

– FileWriter(String fileName, boolean append): An IOException is thrown if the file cannot be opened for appending.

Methods– public void close() throws IOException: Flush the stream and close the file.

– public void flush() throws IOException: Flush the stream.

– public void write(String str) throws IOException: Write a string.

Page 19: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

FileWriter

2019-06-12 Seong Jong Choi Java Basic IO-19

FileWriter

PrintWriterBufferedWriter

JavaProgram Disk

File

주기능

– 내부 16-bit char를 UTF로변환하여파일에저장한다.

Constructors– FileWriter(String fileName) : An IOException is thrown if the file cannot be created.

– FileWriter(String fileName, boolean append): An IOException is thrown if the file cannot be opened for appending.

Methods– public void close() throws IOException: Flush the stream and close the file.

– public void flush() throws IOException: Flush the stream.

– public void write(String str) throws IOException: Write a string.

Page 20: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

BufferedWriter

2019-06-12 Seong Jong Choi Java Basic IO-20

FileWriter

PrintWriterBufferedWriter

JavaProgram Disk

File

주기능

– 버퍼를 사용하여 성능을 향상시킨다.

ConstructorBufferedWriter(Writer out) : Construct a buffered character-output stream

Example: BufferedWriter out = new BufferedWriter(new FileWriter("stuff.txt"));

Page 21: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

PrintWriter

2019-06-12 Seong Jong Choi Java Basic IO-21

FileWriter

PrintWriterBufferedWriter

JavaProgram Disk

File

주기능

– End-of-line 문제해결, 포맷, 기타….

• Constructors– PrintWriter(Writer out) : Create a new PrintWriter and connect it to the Writer out. Automatic line flushing is

not enabled.

– PrintWriter(Writer out, boolean autoFlush) : Create a new PrintWriter and connect it to the Writer out. Automatic line flushing is enabled if autoFlush is true.

• Methods: no execption throwing!!!– public boolean checkError(): Flush the stream. If there has been an error in output the method returns true.

– public void close() : Flush the stream and close the file.

– public void flush() : Flush the stream.

– public void print(char c): Print the character held in c.

– public void print(double d): Translate into characters and print the double value d.

– public void print(float f): Translate into characters and print the float value f.

– public void print(int i): Translate into characters and print the int value i.

– public void print(String s): Print the String s.

– public void print( various other data types ): See your complete documentation.

– public void println(): Terminate the current output line and (possibly) flush the stream.

– public void println( various data types ): See Java on-line documentation.

Page 22: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

Character Read: Reader

• Reader is an abstract class from which all character-oriented input streams are derived. These streams deliver 16-bit

char data to a program. The source of the data may be in a variety of formats (such as UTF format on a disk file). The

diagram shows several Reader classes.

• All these classes are character-oriented input streams. Don't memorize this diagram. Only a few classes are discussed in

these notes; mostly FileReader.

• An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into

characters using a specified charset.

2019-06-12 Seong Jong Choi Java Basic Concepts-22

Page 23: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

Character Read: All-in-one

2019-06-12 Seong Jong Choi Java Basic IO-23

//http://chortle.ccsu.edu/java5/Notes/chap84/ch84_4.html

import java.io.*;

class ReadTextFile {

public static void main ( String[] args ) {

String fileName = "reaper.txt" ;

String line;

try{

BufferedReader in = new BufferedReader( new FileReader( fileName ) );

line = in.readLine();

while ( line != null ) { // while not end of file

System.out.println( line );

line = in.readLine();

}

in.close();

}

catch ( IOException iox ) {

System.out.println("Problem reading " + fileName );

}

}

}

FileReaderBufferedReader

JavaProgram Disk

File

Page 24: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

Buffered Streams

import java.io.FileReader;

import java.io.FileWriter;

import java.io.BufferedReader;

import java.io.PrintWriter;

import java.io.IOException;

public class CopyLines {

public static void main(String[] args) throws IOException {

BufferedReader inputStream = null;

PrintWriter outputStream = null;

try {

inputStream = new BufferedReader(new FileReader("xanadu.txt"));

outputStream = new PrintWriter(new FileWriter("characteroutput.txt"));

String l;

while ((l = inputStream.readLine()) != null) {

outputStream.println(l);

}

} finally {

if (inputStream != null) {

inputStream.close();

}

if (outputStream != null) {

outputStream.close();

}

}

}

}

2019-06-12 Seong Jong Choi Java Basic Concepts-24

FileReader BufferedReader

FileWriter

Program

CopyLines

PrintWriter

Connection Stream

Chain Stream

Page 25: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

Data Stream

• handle binary I/O of primitive data type and

String values

2019-06-12 Seong Jong Choi Java Basic Concepts-25

Page 26: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

File I/O: Stream Class Chaining

2019-06-12 Seong Jong Choi Java Basic Concepts-26

FileOutputStreamDataOutputStream BufferedOutputStream

ObjectOutputStream

FileInputStreamBufferedInputStreamDataInputStream

ObjectInputStream

FileWriter

PrintWriterBufferedWriter

FileReaderBufferedReader

JavaProgram Disk

File

Page 27: Java Basic Concepts - UOSmmlab.uos.ac.kr/OOPJava/Archive/Java Tutorial-Basic IO.pdf2019-06-12 Seong Jong Choi Java Basic Concepts-7 Stream Chaining • Connection Streams – Represents

FileWriter Example

import java.io.*;

class WriteTextFile

{

public static void main ( String[] args ) throws IOException //IOException is a checked exception.

{

String fileName = "reaper.txt" ;

FileWriter writer = new FileWriter( fileName ); // if there is a file with a same name it will delete it and create a new one.

writer.write( "Behold her, single in the field,\n" ); //this is for unix, for Windows use \r\n

writer.write( "Yon solitary Highland Lass!\n" );

writer.write( "Reaping and singing by herself;\n" );

writer.write( "Stop here, or gently pass!\n" );

writer.close();

}

}

//you can easily manipulate text line printing with PrintWrite class.

2019-06-12 Seong Jong Choi Java Basic IO-27


Recommended