09-Java Input Output

Similar documents
Network Programming

<4D F736F F F696E74202D20C1A63234C0E520C0D4C3E2B7C228B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

자바입출력구조 자바입출력 파일 기본입출력 필터입출력 문자입출력 비순차접근파일 객체입출력 파일입출력 바이트배열입출력 파이프입출력 연결형입력 스트링버퍼입력 스트림 ( 순차접근 ) 자바입출력구조

PowerPoint Presentation

12-file.key

PowerPoint 프레젠테이션

자바-11장N'1-502

파일로출력하는작업순서 1. 파일을연다. 2. 파일로자료를쓴다. 3. 파일을닫는다. 파일입출력에사용되는클래스들. FileInputStream, FileOutputStream, FileReader, FileWriter 문자단위로입출력하기 사람이읽을수있는문자로만구성된파일을읽

Java

Microsoft PowerPoint - 04-UDP Programming.ppt

제11장 자바 입출력

PowerPoint 프레젠테이션

Cluster management software

Microsoft PowerPoint - Supplement-03-TCP Programming.ppt [호환 모드]

제11장 자바 입출력

rmi_박준용_final.PDF

Microsoft PowerPoint - 03-TCP Programming.ppt

13-Java Network Programming

02 C h a p t e r Java

PowerPoint 프레젠테이션

비긴쿡-자바 00앞부속

java.lang 패키지 java.util 패키지 java.io 패키지 콜렉션 2

<4D F736F F F696E74202D20C1A63235C0E520B3D7C6AEBFF6C5A920C7C1B7CEB1D7B7A1B9D628B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

Chap12

07 자바의 다양한 클래스.key

Java 자바야놀자 스트림 (Streams) 입출력을이해하기전에스트림이라는용어부터알아야합니다. 스트림은 source에서, sink로의데이터흐름을말합니다. source는데이터흐름의출발점이며, sink는데이터흐름이끝나는지점을의미합니다. source로부터나오는데이

Connection 8 22 UniSQLConnection / / 9 3 UniSQL OID SET

03-JAVA Syntax(2).PDF

JMF3_심빈구.PDF

PowerPoint 프레젠테이션

JAVA PROGRAMMING 실습 09. 예외처리

05-class.key

PowerPoint 프레젠테이션

5장.key

제11장 프로세스와 쓰레드

12-file.key

자바 프로그래밍

JMF2_심빈구.PDF

歯NetworkKawuiBawuiBo.PDF

JavaGeneralProgramming.PDF

14-Servlet

Microsoft PowerPoint - java1-lab5-ImageProcessorTestOOP.pptx

歯JavaExceptionHandling.PDF

歯9장.PDF

PowerPoint Presentation

PowerPoint Presentation

PowerPoint Presentation

Microsoft PowerPoint - java1-lecture9.ppt [호환 모드]

[ 정보 ] 과학고 R&E 결과보고서 Monte Carlo Method 를이용한 고교배정시뮬레이션 연구기간 : ~ 연구책임자 : 강대욱 ( 전남대전자컴퓨터공학부 ) 지도교사 : 최미경 ( 전남과학고정보 컴퓨터과 ) 참여학생 : 박진명 ( 전

class InetAddress3{ public static void main(string[] args) throws Exception{ String url = null ; Scanner reader = new Scanner(System.in); System.out.p

01-OOPConcepts(2).PDF

Microsoft PowerPoint - Java7.pptx

Cluster management software

untitled

PowerPoint 프레젠테이션

09-interface.key

자바로

Java ~ Java program: main() class class» public static void main(string args[])» First.java (main class ) /* The first simple program */ public class

파일로입출력하기II - 파일출력클래스중에는데이터를일정한형태로출력하는기능을가지고있다. - PrintWriter와 PrintStream을사용해서원하는형태로출력할수있다. - PrintStream은구버전으로가능하면 PrintWriter 클래스를사용한다. PrintWriter

목차 INDEX JSON? - JSON 개요 - JSONObject - JSONArray 서울시공공데이터 API 살펴보기 - 요청인자살펴보기 - Result Code - 출력값 HttpClient - HttpHelper 클래스작성 - JSONParser 클래스작성 공공

ch09

: 1 int arr[9]; int n, i; printf(" : "); scanf("%d", &n); : : for(i=1; i<10; i++) arr[i-1] = n * i; for(i=0; i<9; i++) if(i%2 == 1) print

Microsoft PowerPoint - RMI.ppt

교육2 ? 그림

PowerPoint Presentation

10장.key

자바GUI실전프로그래밍2_장대원.PDF

Microsoft PowerPoint - java2-lecture2.ppt [호환 모드]

Contents Contents 2 1 Abstract 3 2 Infer Checkers Eradicate Infer....

슬라이드 1

rosaec_workshop_talk

Data Provisioning Services for mobile clients

PowerPoint Presentation

Java XPath API (한글)

Spring Boot/JDBC JdbcTemplate/CRUD 예제

PowerPoint Presentation

10.

슬라이드 1

Microsoft PowerPoint 자바-기본문법(Ch2).pptx

fundamentalOfCommandPattern_calmglow_pattern_jstorm_1.0_f…

Contents Exceptions

Java ...

신림프로그래머_클린코드.key

mytalk

PowerPoint Presentation

FileMaker ODBC and JDBC Guide

스레드의우선순위 우선순위설정메소드 : void setpriority(int newpriority) newpriority 에설정할수있는등급 : 1( 가장낮은우선순위 ) 부터 10( 가장높은우선순위 ) 가장높은우선순위 : MAX_PRIORITY, 보통우선순위 : NORM_

chap7.key

스레드를적용하지않은결과와스레드를적용한결과의비교 1) 두개의작업을스레드를사용하지않고수행한예 ) : 순차작업 class ThreadTest2 { System.out.print("-");// 화면에 - 를출력하는작업 System.out.print(" ");// 화면에 를출력

11 템플릿적용 - Java Program Performance Tuning (김명호기술이사)

Microsoft PowerPoint - 2강

JAVA PROGRAMMING 실습 02. 표준 입출력

개발문서 Oracle - Clob

MasoJava4_Dongbin.PDF

<443A5C4C C4B48555C B3E25C32C7D0B1E25CBCB3B0E8C7C1B7CEC1A7C6AE425CBED0C3E0C7C1B7CEB1D7B7A55C D616E2E637070>

목차 JEUS EJB Session Bean가이드 stateful session bean stateful sample 가이드 sample source 결과확인 http session에

Modern Javascript

슬라이드 1

PowerPoint Presentation

FileMaker ODBC and JDBC Guide

Transcription:

JAVA Programming Language JAVA Input/Output 2

(1) (Stream) 2,,,,, 3 (2) InputStream OutputStream, 8 Reader Writer, 16 4

(3) Data Source/Dest. (byte stream) InputStream OutputStream Java Internal (byte, byte[ ]) < > Data Source/Dest. (byte stream) Character Encoding Reader Writer < > Unicode Java Internal (char, char[ ], String) 5 (4) OutputStream InputStream 6

(5) Reader Writer 7 (6) Reader BufferedReader LineNumberReader CharArrayReader InputStreamReader FileReader FilterReader PushbackReader PipedReader StringReader Writer / /, /, / / / / (pushback) PipedReader/PipedOutputStream InputStream BufferedInputStream LineNumberInputStream ByteArrayInputStream (none) FileInputStream FilterInputStream PushbackInputStream PipedInputStream StringBufferInputStream OutputStream BufferedWriter /, BufferedWriter BufferedOutputStream CharArrayWriter / / ByteArrayOutputStream FiterWriter / FilterOutputStream OutputStreamWriter FileWriter PrintWriter PipedWriter StringWriter / Writer/Streamdp PipedReader/PipedOutputStream (none) FileOutputStream PrintStream PipedOutputStream (none) 8

(1) InputStream, abstract int read( ) throws IOException int read(byte b[ ]) throws IOException int read(byte b[ ], int off, int len) throws IOException int available( ) throws IOException long skip(long n) throws IOException synchronized void mark(int readlimit) synchronized void reset( ) throws IOException void close( ) throws IOException 9 (2) InputStream import java.io.*; class InputStreamTest { public static void main(string args[ ]) { int ch; InputStream in = System.in; try { while((ch=in.read())!= -1) { if(ch == 'S') { in.skip(2); System.out.println("Char: "+(char)ch+", Available: "+in.available( )); catch(ioexception e) { System.out.println(e); 10

(3) OutputStream, abstract void write(int b) throws IOException void write(byte b[ ]) throws IOException void write(byte b[ ], int off, int len) throws IOException void flush( ) throws IOException void close( ) throws IOException 11 (4) OutputStream import java.io.*; class OutputStreamTest { public static void main(string args[ ]) { OutputStream out = System.out; int ch=0x0fffff00 + 'A'; try { out.write(ch); out.flush( ); // (a) // out.close( ); // (b) catch(ioexception e) { System.out.println(e); 12

(5) Reader, boolean ready( ); int read( ); int read(char[ ] cbuf); abstract int read(char[ ] cbuf, int off, int len); boolean marksupported( ); void mark(int readaheadlimit); void reset( ); long skip(long n); abstract void close( ); 13 (6) Writer, void write(int c ); void write(char[ ] cbuf); abstract void write(char[ ] cbuf, int off, int len); void write(string str); void write(string str, int off, int len); abstract void flush( ); abstract void close( ); 14

(1) FileInputStream FileInputStream FileInputStream // File FileInputStream(File file); // FileDescriptor FileInputStream(FileDescriptor fdobj); // FileInputStream(String name); 15 (2) FileOutputStream File FileOutputStream // File FileOutputStream(File file); // FileDescriptor FileOutputStream(FileDescriptor fdobj); // FileOutputStream(String name); // append FileOutputStream(String name, boolean append); 16

(3) import java.io.*; import java.lang.boolean; class FileInputOutputStreamTest { public staticvoid main(string[] args) { booleanappend = false ; int i, len=0; InputStream in=null; OutputStream out=null; if(args.length < 2) { System.out.println("USAGE: FileInputOutputStreamTest Source_file Destination_file"); System.exit(-1); else if(args.length > 2) { append = newboolean(args[2]).booleanvalue(); System.out.println("args[0]: "+args[0]); System.out.println("args[1]: "+args[1]); System.out.println(" append: "+append); try { in = newfileinputstream(newfile(args[0])); out = newfileoutputstream(args[1], append); catch(filenotfoundexception e) { System.out.println(e); try { while((i=in.read())!= -1) { out.write(i); len++; in.close(); out.close(); System.out.println(len+" bytes are copied..."); catch(ioexception e) { System.out.println(e); 17 (4) FileReader FileWriter // FileReader FileReader(File file); FileReader(FileDescriptor fd); FileReader(String filename); // FileWriter FileWriter(File file); FileWriter(FileDescriptor fd); FileWriter(String filename); FileWriter(String filename, boolean append); 18

(5) import java.io.*; import java.lang.boolean; class FileReaderWriterTest { public staticvoid main(string[] args) { booleanappend = false ; int i, len=0; FileReaderin=null; FileWriterout=null; if(args.length < 2) { System.out.println("USAGE: FileReaderWriterTest Source_file Destination_file"); System.exit(-1); else if(args.length > 2) { append = newboolean(args[2]).booleanvalue(); System.out.println("args[0]: "+args[0]); System.out.println("args[1]: "+args[1]); System.out.println(" append: "+append); try { in = newfilereader(newfile(args[0])); out = newfilewriter(args[1], append); catch(filenotfoundexception e) { System.out.println(e); catch(ioexception e) { System.out.println(e); try { while((i=in.read())!= -1) { out.write(i); len++; in.close(); out.close(); System.out.println(len+" bytes are copied..."); catch(ioexception e) { System.out.println(e); 19 (1) SequenceInputStream SequenceInputStream // Enumeration SequenceInputStream(Enumeration) // 2 SequenceInputStream(InputStream s1, InputStream s2) 20

(2) SequenceInputStream import java.io.*; class SequenceInputTest { public static void main(string[] args) throws IOException { int ch; byte arr1[] = { (byte )'H',(byte )'e',(byte )'l',(byte )'l',(byte )'o' ; byte arr2[] = { (byte )',',(byte )' ' ; ByteArrayInputStream in1 = new ByteArrayInputStream(arr1); ByteArrayInputStream in2 = new ByteArrayInputStream(arr2); FileInputStream in3 = new FileInputStream("SequenceInputTest.txt"); java.util.vector v = new java.util.vector(); v.add(in1); v.add(in2); v.add(in3); in3.reset(); SequenceInputStream in = new SequenceInputStream(v.elements()); while((ch=in.read())!= -1) { System.out.write(ch); System.out.flush(); System.out.println(); in1.reset(); if(in3.marksupported()) { System.out.println("reset()"); else { in3 = new FileInputStream("SequenceInputTest.txt"); System.out.println("newFileInputStream(\"SequenceInputTest.txt\")"); in = newsequenceinputstream(in1, in3); while((ch=in.read())!= -1) { System.out.print((char)ch); System.out.println(); 21 (3) PipedInputStream, PipedOutputStream 22

(4) PipedInputStream PipedOutputStream Java Program (Producer) PipedOutputStream PIPE PipedInputStream Java Program (Consumer) <Pipe > //PipedInputStream PipedInputStream( ); PipedInputStream(PipedOutputStream src); void connect(pipedoutputstream src); // PipedOutputStream PipedOutputStream( ); PipedOutputStream(PipedInputStream snk); void connect(pipedinputstream snk); 23 (5) PipedReaderStream PipedWriterStream //PipedReaderStream PipedReader( ); PipedReader(PipedWriter src); void connect(pipedwriter src); // PipedWriterStream PipedWriter( ); PipedWriter(PipedReader snk); void connect(pipedreader snk); 24

(6) PipedInputStream PipedOutputStream public PipedOutputStream getpipedoutput() { import java.io.*; class PipedInputThread extends Thread {... PipedInputThread () { public PipedInputStream getpipedinput() {......... public void connect(pipedoutputstream pout) { try { public void run() { class PipedOutputThread extends Thread {... PipedOutputThread() { pout = new PipedOutputStream();... public void connect(pipedinputstream pin) {... public void run() { try {... catch(ioexception e) { System.out. println(tostring() + ": "+e); public class PipedInputOutputTest { public static void main(string args[]) { PipedInputThread pin = null; PipedOutputThread pout = null; pin = new PipedInputThread(); pout = new PipedOutputThread(); pin.connect(pout. getpipedoutput()); pin.start(); pout.start(); 25 (1), ByteArrayInputStream ByteArrayOutputStream CharArrayReader CharArrayWriter StringBufferInputStream StringReader StringWriter 26

(2) ByteArrayInputStream (protected byte[ ] buf) ByteArrayOutputStream // ByteArrayInputStream ByteArrayInputStream(byte[ ] buf); ByteArrayInputStream(byte[ ] buf, int offset, int length); // ByteArrayOutputStream ByteArrayOutputStream( ); ByteArrayOutputStream(int size); String tostring( ); String tostring(string enc); 27 (3) ByteArrayInputStream ByteArrayOutputStream import java.io.*; class ByteArrayInputOutputTest { public staticvoid main(string[] args) throws IOException { int ch; byte arr[] = { (byte)'j',(byte)'a',(byte)'v',(byte)'a',(byte)'!' ; ByteArrayInputStream in = new ByteArrayInputStream(arr); ByteArrayOutputStream out = newbytearrayoutputstream(); FileOutputStream outfile = newfileoutputstream("bytearrayinputoutputtest.txt"); while((ch=in.read())!= -1) { out.write(ch); System.out.println(" read: ["+(char)ch+"]" +", write: ["+out.tostring () +"]"+out.size()); System.out.println("String: "+out.tostring()); out.writeto(outfile); 28

(4) CharArrayReader CharArrayWriter // CharArrayReader CharArrayReader(char[ ] buf); CharArrayReader(char[ ] buf, int offset, int length); //CharArrayWriter CharArrayWriter( ); CharArrayWriter(int initialsize); int size( ); void writeto(write out);... 29 (5) CharArrayReader CharArrayWriter import java.io.*; class CharArrayReaderWriterTest { public static voidmain(string[ ] args) throws IOException { int ch; chararr[ ] = { 'H','e','l','l','o',',',' ','J','a','v','a','!' ; CharArrayReaderin; CharArrayWriter out; in = new CharArrayReader(arr, 7, 5); out = newchararraywriter( ); while((ch=in.read( ))!= -1) { out.write(ch); System.out.println("read: ["+(char)ch+"]"+", write: ["+out.tostring()+"]"+out.size( )); System.out.println(" String: "+out.tostring()); 30

(6) StringBufferInputStream 1. StringBufferInputStream // StringBufferInputStream(String s); 31 (7) StringBufferInputStream import java.io.*; class StringBufferInputTest { public static void main(string[ ] args) throws IOException { int ch; String s = "Hi~"; StringBufferInputStream in = new StringBufferInputStream(s); while((ch=in.read())!= -1) { System.out.println("read: ["+(char)ch+","+ch+"]"+in.available( )); 32

(8) StringReader StringWriter // StringReader StringReader(String s); // StringWriter StringWriter( ); StringWriter(int initialsize); StringBuffer getbuffer( ); String tostring( ); 33 (9) StringReader StringWriter import java.io.*; class StringReaderWriterTest{ publicstatic void main(string[]args) throws IOException { int ch; String s = "Hello, Java!"; StringReader in = newstringreader(s); StringWriter out = newstringwriter(s.length()/2); in.skip(7); while((ch=in.read())!= -1) { out.write(ch); System.out.println("read: ["+(char)ch+"]" +", write: ["+out.tostring()+"]" +out.getbuffer().length()); System.out.println(" out: "+out.tostring()); System.out.println(" out: "+out.getbuffer().reverse()); in = newstringreader(out.tostring()); CharArrayWriterout2 = newchararraywriter(); while((ch=in.read())!= -1) { out2.write(ch); System.out.println("read: ["+(char)ch+"]"+", write: ["+out2.tostring()+"]"+out2.size() out2.writeto(out); System.out.println(" out: "+out.tostring()); System.out.println("out2: "+out2.tostring()); 34

(1) 1. : FilterInputStream / FilterOutputStream FilterReader / FilterWriter 2. : BufferedInputStream / BufferedOutputStream, BufferedReader / BufferedWriter 3. : DataInputStream / DataOutputStream 4. : LineNumberInputStream / LineNumberReader 5. : PushbackInputStream / PushbackReader 6. : PrintStream / PrintWriter Java Program FilterInputStream FilterOutputStream InputStream OutputStream <Filter > Data Source / Destination 35 (2) FilterInputStream FilterOutputStream FilterReader FilterWriter 36

(3) BufferedInputStream mark reset BufferedOutputStream BufferedReader BufferedWriter 37 (4) DataInputStream, DataOutputStream 38

(5) LineNumberInputStream JDK1.1 LineNumberReader LineNumberReader LineNumberInputStream 39 (5) import java.io.*; class LineNumberInputTest { public static voidmain(string[]args) { int ch, i=-1; LineNumberInputStream in=null; try { FileInputStream fin = newfileinputstream("test.java"); in = new LineNumberInputStream(fin); catch(filenotfoundexceptione) { System.out.println(e); try { while((ch=in.read())!= -1) { if(i!= in.getlinenumber()) { i = in.getlinenumber(); if(i >= 10) { in.setlinenumber(0); i = in.getlinenumber(); System.out.print("currline: "+i+", "); System.out.println(); catch(ioexceptione) { System.out.println(e); 40

(6) PushbackInputStream PushbackReader 41 (6) import java.io.*; class PushbackInputTest { public static int readnum(pushbackinputstream in) { int i, ch; i=0; try { while(((ch=in.read())!= -1)&((ch >= '0')&&(ch <= '9'))) { i = (i * 10) + (ch - '0'); in.unread(ch); catch(ioexception e) { System.out.println(e); return(i); 42

(6) ( ) public static voidmain(string[ ] args) { int ch, i=-1; int op1, op2; charopr='\u0000'; PushbackInputStream in=new PushbackInputStream(System.in); op1 = readnum (in); try { opr = (char)in.read( ); catch(ioexception e) { System.out.println(e); op2 = readnum (in); switch(opr) { case '+': System.out.println(op1+" "+opr+" "+op2+" = "+(op1+op2)); break; case '-': System.out.println(op1+" "+opr+" "+op2+" = "+(op1-op2)); break; case '*': System.out.println(op1+" "+opr+" "+op2+" = "+(op1*op2)); break; case '/': System.out.println(op1+" "+opr+" "+op2+" = "+(op1/op2)); break; 43. ObjectInputStream ObjectOutputStream 44

ObjectInputStream / ObjectOutputStream, ObjectInput / ObjectOutput 45 ObjectInput DataInout // ObjectInput int available( ); int read( ); int read(byte[ ] b); // //. //. int read(byte[ ] b, int off, int len); //. Object readobject( ); //. long skip(long n); void close( ); //. //. 46

ObjectOutput DataOutput // ObjectOutput void write(byte[ ] b); void write(byte[ ] b, int off, int len); void write(int b); // // void writeobject(object obj); // void flush( ); void close( ); // flush //. // 47 ObjectInputStream ObjectOutputStream // ObjectInputStream FileInputStream istream = new FileInputStream( t.tmp ); ObjectInputStream p = new ObjectInputStream(istream); int i = p.readint( ); String today = (String)p.readObject( ); Date data = (Date)p.readObject( ); istream.close( ); 48

ObjectOutputStream // ObjectOutputStream FileOutputStream ostream = new FileOutputStream( t.tmp ); ObjectOutputStream p = new ObjectOutputStream(ostream); p.writeint(12345); p.writeobject( Today ); p.writeobject(new Date( )); p.flush( ); ostream.close( ); 49 Serializable. Serializable wirteobject readobject Externalizable Serializable writeexternal readexternal 50

import java.io.*; class ObjectData implements Serializable { String name; int age; float height; private void readobject(objectinputstream stream) throws IOException, ClassNotFoundException { stream.defaultreadobject(); System.out.print(" readobject: "); public ObjectData () { this("noname", 0, 0.0f); public ObjectData (String name, int age, float height) { this.name = name; this.age = age; this.height = height; public String tostring() { return("name: "+name+", age: "+age+", height: " + height); class ObjectInputOutputTest { public static void main(string[] args) { ObjectData [] data = new ObjectData [3]; private void writeobject(objectoutputstream stream) throws IOException { stream.defaultwriteobject(); System.out.print("writeObject: "); data[0] = new ObjectData ("Yongwoo", 26, 168f); data[1] = new ObjectData ("Kildong ", 19, 174.8f); data[2] = new ObjectData ("Dongsoo ", 30, 169.4f); try { FileOutputStream outf = new FileOutputStream("ObjectInputOutputTest.txt"); ObjectOutput out = newobjectoutputstream(outf); 51 ( ) out.writeint(data.length); System.out.println("Number: "+data.length); for(int i=0;i<data.length;i++) { out.writeobject(data[i]); System.out.println(data[i]); out.close(); FileInputStream inf = new FileInputStream("ObjectInputOutputTest.txt"); ObjectInput in = new ObjectInputStream(inf); int numberofdata ; ObjectData objdata ; numberofdata = in.readint(); System.out.println("Number: "+numberofdata ); for(int i=0;i<numberofdata ;i++) { objdata = (ObjectData )in.readobject(); System.out.println(objData); in.close(); catch(exception e) { e.printstacktrace(); 52

RandomAccessFile,.., RandomAccessFile 53 RandomAccessFile // RandomAccessFile RandomAccessFile(String name, String mode); RandomAccessFile(File file, String mode); void seek(long pos); // long getfilepointer( ); // long length( ); // 54

RandomAccessFile import java.io.*; publicclass RandomAccessFileTest { public staticvoid main(string[ ] args)throws IOException { RandomAccessFile f; f = newrandomaccessfile("randomaccessfile.txt", "rw"); for(int i=0;i<100;i++) { f.writeint(i); for(int i=0;i<10;i++) { int accpointer= (int)(math.random( )*100); f.seek(accpointer* 4); System.out.print("Current FP: " + f.getfilepointer( )); System.out.println(", Data: " + f.readint( )); f.close(); C:\>javac RandomAccessFileTest.java C:\>java RandomAccessFileTest Current FP: 20, Data: 5 Current FP: 72, Data: 18 Current FP: 256, Data: 64 Current FP: 104, Data: 26 Current FP: 304, Data: 76 Current FP: 40, Data: 10 Current FP: 96, Data: 24 Current FP: 168, Data: 42 Current FP: 96, Data: 24 Current FP: 324, Data: 81 C:\> 55