1 / 51

Java 파일 입출력

Java 파일 입출력. Chap 10. Java 파일 입출력. 자바의 입출력은 모든 하드웨어에 독립적으로 설계 자바는 입출력을 스트림 (Stream) 으로 처리 사용자는 스트림을 이용하여 입출력 수행 스트림을 이용하여 실제 다양한 하드웨어와 입출력을 수행하는 일은 JVM 에 의해 실행 자바는 입출력을 위한 클래스로 java.io 패키지제공. Chap 10. Java 파일 입출력. 스트림 (stream) 의 개요 스트림 : 순서가 있는 일련의 데이터를 의미하는 추상적인 의미 입출력 데이터의 흐름

fran
Download Presentation

Java 파일 입출력

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java 파일 입출력

  2. Chap 10. Java 파일 입출력 • 자바의 입출력은 모든 하드웨어에 독립적으로 설계 • 자바는 입출력을 스트림(Stream)으로 처리 • 사용자는 스트림을 이용하여 입출력 수행 • 스트림을 이용하여 실제 다양한 하드웨어와 입출력을 수행하는 일은 JVM에 의해 실행 • 자바는 입출력을 위한 클래스로 java.io 패키지제공

  3. Chap 10. Java 파일 입출력 • 스트림(stream) 의 개요 • 스트림 : 순서가 있는 일련의 데이터를 의미하는 추상적인 의미 • 입출력 데이터의 흐름 • 데이터의 형식이나 길이가 정해지지 않음. • 문자형(16 비트) 또는 바이트형(8비트) 데이터의 일렬 이동 • 네트워크 소켓 프로그램에도 적용됨

  4. 10. 파일 입출력 • java.io 패키지 • 스트림(stream) • 바이트 스트림 - 바이트의 연속(ex, 이미지 파일 등) • InputStream - 입력 • OutputStream - 출력 • 문자 스트림 - 문자의 연속(ex, text) • Reader - 입력 • Writer - 출력 • System 클래스 • out - PrintStream • in - InputStream

  5. 10. 파일 입출력 • 바이트 스트림 상속 관계 출력 스트림 클래스 상속 관계 입력 스트림 클래스 상속 관계

  6. 10. 파일 입출력 • 문자 스트림 상속 관계 Reader 클래스 상속 관계 Writer 클래스 상속 관계

  7. 10. 파일 입출력 10.1 File 클래스 • 파일과 디렉토리 관련 메소드를 지원 • 생성자 publicFile(Stringpath); publicFile(Stringpath,StringfileName); publicFile(Filedirectory,StringfileName); • 파일의 객체생성 Filef1=newFile("C:\Java\Stream\Test.java"); Filef2=newFile("C:\Java\Stream","Test.java"); Filedir=newFile("C:\Java\Stream");//디렉토리생성 Filef3=newFile(dir,"Test.java");//생성된디렉토리이용

  8. 10. 파일 입출력 10.2 File 클래스 메소드 String getName() 파일의 이름을 반환 long length() 파일의 길이를 반환 String getPath() 파일의 경로를 반환 String getAbsolutePath() 파일의 절대 경로를 반환 String getParent() 파일의 부모 디렉토리를 반환 boolean canWrite() 파일이 쓰기 가능이면 true를 반환 boolean canRead() 파일이 읽기 가능이면 true를 반환 boolean isFile() 현 객체가 파일이면 true를 반환 boolean isDirectory() 현 객체가 디렉토리이면 true를 반환 boolean equals(Object obj) 현 객체와 obj가 동일하면 ture를 반환

  9. 10. 파일 입출력 10.2.1 File 클래스 메소드 longlastModified() 파일의마지막수정시간을밀리초단위로반환 (기준시간:1970년1월1일을0으로시작) booleandelete() 파일을삭제하고true를반환,불가능시false반환 booleanmkdir() 현객체패스이름의디렉토리를생성하고true를반환, 불가능시false반환 String[]list() 디렉토리에서파일이름의배열을반환 booleanrenameTo(Filenew) 파일이나디렉토리이름을new로변경한다음ture를반환, 불가능시false를반환

  10. 10. 파일 입출력 10.2.2 Sample importjava.io.File; classFileDemo1{ publicstaticvoidmain(Stringargs[]){ Stringdir="c:/httpd"; Filef1=newFile(dir); System.out.println("DirectoryName:"+dir); System.out.println("lastModified:"+f1.lastModified()); System.out.println("CanRead?:"+f1.canRead()); System.out.println("CanWrite?:"+f1.canWrite()); System.out.println("isFile?:"+f1.isFile()); System.out.println("isDirectory?:"+f1.isDirectory());

  11. 10. 파일 입출력 10.2.3 Sample System.out.println("---Nowwecheckc:/httpd'ssubdirectory---"); Strings[]=f1.list(); for(inti=0;i<s.length;i++){ Filef=newFile(dir,s[i]); if(f.isDirectory()){System.out.println(s[i]+"isaDirectory"); }else{ System.out.print(s[i]+"isaFile"); System.out.println("&sizeis"+f.length()); } } } }

  12. 10. 파일 입출력

  13. 10. 파일 입출력 10.2.4 결과 C:\JAVA\NewBook\c10>javaFileDemo1 DirectoryName:c:/httpd lastModified:924777402000 CanRead?:true CanWrite?:true isFile?:false isDirectory?:true ---Nowwecheckc:/httpd'ssubdirectory--- IconsisaDirectory LogsisaDirectory HtDocsisaDirectory cgi-binisaDirectory Cgi-WinisaDirectory Uninst.isuisaFile&sizeis12580 License.txtisaFile&sizeis1738 OHTTPd.exeisaFile&sizeis327680

  14. 10. 파일 입출력 10.3 바이트 스트림 - 8비트 데이터 입출력을 위한 스트림 10.3.1 OutputStream 클래스와 InputStream 클래스 - OutputStream 클래스의 메소드 메 소 드 설 명 void close() throws IOException 출력 스트림을 닫는다. void flush() throws IOException 버퍼에 저장된 데이터 모두 출력 void write(int i) throws IOException 정수 i의 하위 8bit를 출력한다. void write(byte buf[]) throws   IOException buf[]의 내용을 출력한다. void write(byte buf[], int index, int size) throws IOException buf[]의 index에서 size만큼의 바이트 출력한다.

  15. 10. 파일 입출력 - InputStream 클래스의 메소드 메 소 드 설 명 void close() throws IOException 입력 스트림을 닫는다. int read() throws IOException 입력 스트림 한 바이트를 읽는다. int read(byte buf[]) throws IOException 입력 스트림에서 buf[]를 읽고, 읽은 바이트 수를 반환한다. int read(byte buf[], int offset, int size) throws  IOException 입력 스트림에서 size만큼 읽고, 읽은 바이트 수를 반환한다. int avaiable() 읽기 가능한 바이트 수를 반환 int skip(long num) num만큼의 바이트를 지나친다. void mark(int numByte) 입력 스트림의 현재 위치에 mark void reset() 입력 스트림의 포인트를 mark위치로 복귀한다.

  16. 10. 파일 입출력 10.3.2 FileOutputStream 클래스와 FileInputStream 클래스 - 이진데이터를 파일에 쓰거나 읽을 수 있도록 한다. o FileOutputStream 클래스 생성자 FileOutputStream(Stringfilepath)throwsIOException FileOutputStream(Stringfilepath,booleanappend)throws IOException FileOutputStream(FilefileObj)throwsIOException o FileInputStream 클래스 생성자 FileInputStream(Stringfilepath)throws FileNotFoundException FileInputStream(FilefileObje)throws FileNotFoundException

  17. 10. 파일 입출력 [예제코드] importjava.io.*; classFileOutputStreamDemo{ publicstaticvoidmain(Stringargs[])throwsIOException{ FileOutputStreamf=newFileOutputStream(args[0]); for(inti=0;i<5;i++) f.write(i); for(charc='A';c<='Z';c++) f.write(c);//문자c를저장 f.close(); } }

  18. 10. 파일 입출력 [실행결과] C:\java\c10>javaFileOutputStreamDemofs.dat C:\java\c10>typefs.dat ?!$%~ABCDEFGHIJKLMNOPQRSTUV

  19. 10. 파일 입출력 [예제코드] importjava.io.*; classFileInputStreamDemo{ publicstaticvoidmain(Stringargs[])throwsIOException{ FileInputStreamf=newFileInputStream(args[0]); inti; for(i=0;i<5;i++) System.out.print(f.read()+""); System.out.println(); while((i=f.read())!=-1){//EOFtest System.out.print((char)i+""); } f.close(); } }

  20. 10. 파일 입출력 [실행결과] C:\java\c10>javaFileInputStreamDemofs.dat 01234 ABCDEFGHIJKLMNOPQRSTUVW XYZ

  21. 10. 파일 입출력 10.3.3 DataOutputStream 클래스 o 생성자 DataOutputStream(OutputStream outStream) o DataOutputStream 클래스의 메소드 voidwriteByte(inti)throwsIOException i의하위8비트를출력 voidwriteChar(inti)throwsIOException i의하위16비트를출력 voidwriteChars(Strings)throwsIOException 문자열s를출력 voidwriteDouble(doubled)throwsIOException 실수d를스트림으로출력 voidwriteInt(inti)throwsIOException 정수i를스트림으로출력 voidwriteLong(longl)throwsIOException 정수l을스트림으로출력 voidwriteBoolean(booleanb)throwsIOException boolean형b를스트림으로출력 voidwriteUTF(Strings)throwsIOException Strings를UTF-8로인코딩하여스트림으로출력

  22. 10. 파일 입출력 [예제코드] importjava.io.*; classDataOutputStreamDemo{ publicstaticvoidmain(Stringargs[]){ try{ FileOutputStreamf=newFileOutputStream(args[0]); DataOutputStreamds=newDataOutputStream(f); byteb=24; inti=1024; longl=10241024; doubled=12.12345; Strings="Yaho!Java"; ds.writeBoolean(false); ds.writeByte(b);

  23. 10. 파일 입출력 [예제코드] ds.writeChar('K'); ds.writeInt(i); ds.writeLong(l); ds.writeDouble(d); ds.writeUTF(s); ds.close(); } catch(Exceptione){System.out.println("exception:"+e);} } } [실행결과] C:\java\c10>javaDataOutputStreamDemoobj.dat C:\JAVA\NewBook\c10>typeobj.dat K쏡@(?4煉 Yaho!Java

  24. 10. 파일 입출력 10.3.4 DataInputStream o 생성자 DataInputStream(InputStream is) o DataInputStream 클래스의 메소드 bytereadByte()throwsIOException스트림에서읽은byte를반환 charreadChar()throwsIOException스트림에서읽은문자를반환 StringreadLine()throwsIOException스트림에서읽은문자열을반환 shortreadShort()throwsIOException스트림에서읽은short를반환 doublereadDouble()throwsIOException스트림에서읽은double을반환 intreadInt()throwsIOException스트림에서읽은정수를반환 longreadLong()throwsIOException스트림에서읽은long을반환 booleanreadBoolean()throwsIOException스트림에서읽은 boolean을반환 StringreadUTF()throwsIOException UTF로코딩된스트림에서읽은문자열을반환 intskipBytes(intn) 스트림에서n바이트를건너뜀

  25. 10. 파일 입출력 [예제코드] importjava.io.*; classDataInputStreamDemo{ publicstaticvoidmain(Stringargs[]){ try{ FileInputStreamf=newFileInputStream(args[0]); DataInputStreamds=newDataInputStream(f); booleanbb=ds.readBoolean(); byteb=ds.readByte(); charc=ds.readChar(); inti=ds.readInt(); longl=ds.readLong(); doubled=ds.readDouble(); Strings=ds.readUTF(); System.out.println("boolean="+bb); System.out.println("byte="+b); System.out.println("char="+c);

  26. 10. 파일 입출력 [예제코드] System.out.println("long="+l); System.out.println("double="+d); System.out.println("String="+s); ds.close(); } catch(Exceptione){System.out.println("exception:"+e);} } } [실행결과] C:\JAVA\NewBook\c10>javaDataInputStreamDemoobj.dat boolean=false byte=24 char=K long=10241024 double=12.12345 String=Yaho!Java

  27. 10. 파일 입출력 10.4 문자 스트림 10.4.1 Writer 클래스와 Reader 클래스 - 추상 클래스 - 문자 입출력에 필요한 기본 메소드를 정의 o Writer 클래스의 메소드 voidclose() 출력스트림을닫음 voidflush() 버퍼에저장된데이터를출력 voidwrite(intc) c의하위16비트를출력 voidwrite(charbuf[]) buf[]의문자들을출력 voidwrite(charbuf[],intindex,intsize) buf[]의index에서size만큼의문자들을출력 voidwrite(Strings) 문자열s를출력 voidwrite(Strings,intindex,intsize) 문자열의index에서size만큼의문자들을출력

  28. 10. 파일 입출력 o Reader 클래스의 메소드 voidclose() 입력스트림을닫음 intread() 스트림에서다음문자를읽어반환 intread(charbuf[]) 스트림에서buf[]만큼의문자를읽음 intread(charbuf[],intoffset,intsize) 스트림에서size만큼의문자를읽어서buf[]의offset 위치에저장,반환값은읽은문자수임 voidmark(intnumChars) 입력스트림의현재위치에mark booleanmarkSupported() 현입력스트림의mark()지원여부를반환 booleanready() 현입력스트림에서read()문을수행가능여부를반환 voidreset() 입력스트림의현재위치에서가장가까운mark표시로이동 intskip(longnumChars) 입력스트림에서numChars 수만큼의 문자를건너뛰고실제건너뛴문자수를반환

  29. 10. 파일 입출력 10.4.2 FileWriter 클래스와 FileReader 클래스 o FileWriter 클래스의 생성자 FileWriter(Stringfilepath)throwsIOException FileWriter(Stringfilepath,booleanappend)throwsIOException FileWriter(Filefileobj)throwsIOException [예제코드] importjava.io.*; publicclassFileWrite1 publicstaticvoidmain(Stringargs[])throwsIOException { FileWriterfw=newFileWriter(args[0]); for(intx=1;x<=10;x++) fw.write("Linenumber:"+x+"\n"); fw.close(); } } [실행결과] C:\java\c10>javaFileWrite1data.txt

  30. 10. 파일 입출력 o FileReader 클래스의 생성자 FileReader(Stringfilepath)throwsFileNotFoundException FileReader(FilefileObj)throwsFileNotFoundException [예제코드] importjava.io.*; publicclassFileRead1 { finalstaticintEOF=-1; publicstaticvoidmain(Stringargs[])throwsIOException { FileReaderf=newFileReader(args[0]); intch; while((ch=f.read())!=EOF) System.out.print((char)ch); f.close(); } }

  31. 10. 파일 입출력 [실행결과] C:\java\c10>javaFileRead1data.txt Linenumber:1 Linenumber:2 Linenumber:3 Linenumber:4 Linenumber:5 Linenumber:6 Linenumber:7 Linenumber:8 Linenumber:9 Linenumber:10

  32. 10. 파일 입출력 10.4.3 OutputStreamWriter 클래스 InputStreamReader 클래스 1) OutputStreamWriter 클래스 -문자출력스트림을바이트출력스트림으로변경 o생성자 OutputStreamWriter(OutputStreamos) OutputStreamWriter(OutputStreamos,Stringencoding) 2) InputStreamReader 클래스 -바이트입력스트림을문자입력스트림으로변경 o생성자 InputStreamReader(InputStreamis) InputStreamReader(InputStreamis,Stringencoding) 예)키보드로부터유니코드문자스트림으로변환하는코드 InputSteamReaderinReader=newInputStreamReader(System.in);

  33. 10. 파일 입출력 10.4.4 Buffered 문자 스트림 - 입출력 효율의 향상 - readLine() 메소드 지원 o BufferedWriter 클래스의 생성자 BufferedWriter(Writeros) BufferedWriter(Writeros,intbufsize) o BufferedReader 클래스의 생성자 BufferedReader(Readeris) BufferedReader(Readeris,intbufsize)

  34. 10. 파일 입출력 [예제코드] importjava.io.*; publicclassFileWrite2 { publicstaticvoidmain(Stringargs[]) { BufferedReaderin=newBufferedReader(new InputStreamReader(System.in));//바이트스트림→문자스트림 try{ FileWriterfw=newFileWriter(args[0]); while(true){ System.out.print("Yourinput:"); Stringinput=in.readLine(); if(input.startsWith("end"))break; System.out.println("Yourinputis"+input); fw.write(input+"\r\n"); } fw.close(); } catch(IOExceptione){System.out.println(e);} } }

  35. 10. 파일 입출력 [실행결과] C:\java\c10>javaFileWrite2data.txt Yourinput:Iloveyou YourinputisIloveyou Yourinput:Loveisforever YourinputisLoveisforever Yourinput:end C:\java\c10>typedata.txt Iloveyou Loveisforever

  36. 10. 파일 입출력 10.4.5 StreamTokenizer 클래스 - 문자스트림과 분리자를 입력받아 토큰을 생성 o StreamTokenizer 클래스에서 제공되는 클래스 상수 TT_EOF파일의끝 TT_EOF 라인의끝 TT_NUMBER 읽은토큰이숫자임 TT_WORD읽은토큰이단어임

  37. 10. 파일 입출력 o StreamTokenizer 클래스의 메소드 intlineno() 현재의라인번호를반환 intnextToken()토큰이숫자이면,TT_NUMBER를, 단어이면TT_WORD를,아니면읽은문자를반환 voidlowerCaseMode(booleanflag) flag가true이면,모든토큰이소문자로취급 StringtoString() 현재의토큰과동일한문자열을반환 voidwhitespaceChars(intc1,intc2) c1-c2사이의모든문자를공란으로취급 voidwordChars(intc1,intc2) c1-c2사이의모든문자를단어로취급 voidordinaryChar(inti) i를정규문자로지정

  38. 10. 파일 입출력 [예제코드] importjava.io.*; classStreamTokenizerDemo{ publicstaticvoidmain(Stringargs[])throwsIOException{ InputStreamReaderfr=newInputStreamReader(System.in); StreamTokenizerst=newStreamTokenizer(fr); st.whitespaceChars('a','z'); //영문소문자a-z를공란으로취급 while(st.nextToken()!=StreamTokenizer.TT_EOF){ //다음토큰을읽고,스위치문실행 System.out.print("\t"); switch(st.ttype){ casest.TT_WORD: System.out.println("Line#"+st.lineno()+"Word)"+st.sval); break; casest.TT_NUMBER: System.out.println("Line#"+st.lineno()+"Number)"+st.nval); break; default: System.out.println("Line#"+st.lineno()+"Specialchar)" +(char)st.ttype); }}}}

  39. 10. 파일 입출력 [실행결과] C:\java\c10>javaStreamTokenizerDemo KIMLOVECOMputer!!!123//키보드입력 Line#1Word)KIM Line#1Word)LOVE Line#1Word)COM Line#1Specialchar)! Line#1Specialchar)! Line#1Specialchar)! Line#1Number)123.0 SeeYOU//키보드입력 Line#2Word)S Line#2Word)YOU ^z(control-z는파일의끝을나타냄)

  40. 10. 파일 입출력 10.5 객체의 입출력 10.5.1 ObjectOutputStream/ObjectInputStream - 객체 입출력을 지원하는 클래스 o ObjectOutputStream 클래스의 생성자 ObjectOutputStream(OutputStreamout)throwsIOException 예) FileOutputStreamfs=newFileOutputStream("xyz.dat"); ObjectOutputStreamos=newObjectOutputStream(fs); o ObjectOutputStream 클래스의 주요 메소드 voidwriteObject(Objectobj)throwsIOException객체obj를출력 voidwrite(byteb[])throwsIOException바이트배열b를출력 publicvoidclose()throwsIOException스트림을닫음 -객체입출력을위해서는Serializable인터페이스를 구현하여야한다. 예) classPersonimplementsSerializable{ ........... }

  41. 10. 파일 입출력 o ObjectInputStream 클래스의 생성자 ObjectInputStream(InputStreamin)throws IOException,StreamCorruptedException o ObjectInputStream 클래스의 주요 메소드 ObjectreadObject()throwsIOException,OptionalDataException, ClassNotFoundException 입력스트림에서객체를읽음 intread(byteb[],intoffset,intnumChars)throwsIOException numChars만큼의바이트를읽어배열b의offset에서부터저장 intavailable()throwsIOException 읽을수있는바이트수를반환 intread()throwsIOException 바이트를읽고반환 voidclose()throwsIOException 입력스트림을닫음

  42. 10. 파일 입출력 [객체저장예제코드] importjava.io.*; classPersonimplementsSerializable{ Stringname; intid; Person(Stringname,intid){ this.name=name; this.id=id; } } classSerializePerson{ publicstaticvoidmain(Stringargs[]){ Personp1=newPerson("Kim",7); Personp2=newPerson("Lee",8); Personp3=newPerson("Park",12); try{ FileOutputStreamfs=newFileOutputStream("obj.dat"); ObjectOutputStreamos=newObjectOutputStream(fs); os.writeObject(p1); os.writeObject(p2); os.writeObject(p3); os.close(); System.out.println("dateobjectstored"); }catch(IOExceptione){ e.printStackTrace(); } } }

  43. 10. 파일 입출력 [객체입력예제코드] classPersonimplementsSerializable{ Stringname;intid; Person(Stringname,intid){ this.name=name; this.id=id; } } classUnSerialize{ publicstaticvoidmain(Stringargs[]){ Personp1=null;Personp2=null; Personp3=null; try{ FileInputStreamfs=newFileInputStream("obj.dat"); ObjectInputStreamos=newObjectInputStream(fs); p1=(Person)os.readObject(); p2=(Person)os.readObject(); p3=(Person)os.readObject(); os.close(); }catch(Exceptione){e.printStackTrace();} System.out.println("Person1="+p1.name+""+p1.id); System.out.println("Person2="+p2.name+""+p2.id); System.out.println("Person2="+p3.name+""+p3.id); } } [실행결과] C:\java\c10>javacUnSerialize.java C:\java\c10>javaUnSerialize Person1=Kim7 Person2=Lee8 Person2=Park12

  44. 10. 파일 입출력 10.5.2 객체 배열의 사용 - Person 객체 배열의 선언 Person[] p = new Person[4]; - 각 배열의 요소에 객체 할당 p[0] = new Person("kim", 12);    p[1] = new Person("lee", 7); - p[0]의 메소드 또는 변수 참조 result1 = p[0].m()     result2 = p[0].x

  45. 10. 파일 입출력 [예제코드] classPerson{ Stringname;intid; Person(Stringname,intid){ this.name=name;this.id=id; } publicStringtoString(){ Strings=name+""+id; returns; } publicvoidprint(){ System.out.println("ID#"+id+"\tname:"+name); } } classObjectArray{ publicstaticvoidmain(Stringa[]){ Personp[]={newPerson("Kim",7),newPerson("Lee",4)}; Person[]q=newPerson[2]; q[0]=p[0];//동일한객체를가리킴 q[1]=newPerson("Park",12); p[0].print();//p[0]의메소드접근 q[1].print();//q[1]의메소드접근

  46. 10. 파일 입출력 [예제코드] System.out.println("p[0]="+p[0]); System.out.println("p[1]="+p[1]); System.out.println("q[0]="+q[0]); System.out.println("q[1]="+q[1]); } } [실행결과] C:\JAVA\NewBook\c10>javaObjectArray ID#7name:Kim ID#12name:Park p[0]=Kim7 p[1]=Lee4 q[0]=Kim7 q[1]=Park12

  47. 10. 파일 입출력 10.6RandomAccessFile [RandomWrite.java] importjava.io.*; classTel_Book{ Stringname; inttel_no; Tel_Book(Stringn,intno){ name=n;tel_no=no; } } classRandomWrite{ staticfinalintFILESIZE=40; staticlonghash(Strings){ intaddr=0; for(intk=0;k<s.length();k++) addr+=(k+2)*(int)s.charAt(k); return(long)(addr%FILESIZE); }

  48. 10. 파일 입출력 publicstaticvoidmain(Stringa[])throwsIOException { Tel_Bookp[]={ newTel_Book("Cho",1111), newTel_Book("Jung",4315), newTel_Book("Lee",4157), newTel_Book("Oh",4902), newTel_Book("Park",7878)}; for(intk=0;k<p.length;k++) System.out.println(p[k].name+"\tkey="+hash(p[k].name)); RandomAccessFilef=newRandomAccessFile("tel.dat","rw"); for(intk=0;k<FILESIZE;k++) f.writeInt(0);//save20intvalues for(intk=0;k<p.length;k++){ f.seek(hash(p[k].name)); f.writeInt(p[k].tel_no); }f.close(); } }

  49. 10. 파일 입출력 [실행결과] c:\javaRandomWrite ChoKey=10 JungKey=14 LeeKey=19 OhKey=30 ParkKey=2

  50. 10. 파일 입출력 [RandomRead.java] importjava.io.*; classRandomRead{ staticfinalintFILESIZE=40; staticlonghash(Strings){ intaddr=0; for(intk=0;k<s.length();k++) addr+=(k+2)*(int)s.charAt(k); return(long)(addr%FILESIZE); } publicstaticvoidmain(Stringa[])throwsIOException{ RandomAccessFilef=newRandomAccessFile("tel.dat","r"); BufferedReaderin=newBufferedReader(new InputStreamReader(System.in)); while(true){ System.out.print("KeyName:"); Stringname=in.readLine();

More Related