




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)
文檔簡介
1、第9章 輸入/輸出操作,本章導(dǎo)讀,Java應(yīng)用不是一潭死水,經(jīng)常需要和外界通信。 流是一個很形象的概念,當(dāng)程序需要讀取數(shù)據(jù)的時候,就會開啟一個通向數(shù)據(jù)源的流,這個數(shù)據(jù)源可以是文件、內(nèi)存或是網(wǎng)絡(luò)連接。當(dāng)程序需要寫入數(shù)據(jù)的時候,就會開啟一個通向目的地的流。 Java語言中輸入/輸出功能是通過流類來實現(xiàn)的,通過流,可以讓數(shù)據(jù)以與設(shè)備無關(guān)的方式流動,提高程序的通用性。,本章要點, Java輸入輸出流分類 Java字節(jié)流、字符流、過濾流 Java文件操作類 Java標(biāo)準(zhǔn)輸入輸出流 Java對象序列化機制,9.1 基礎(chǔ)知識,9.1.1 Java輸入/輸出概述 Java流分很多種。按照流中數(shù)據(jù)流動的方向,可
2、分為輸入流和輸出流,若數(shù)據(jù)是從程序外部流入程序內(nèi)部,則稱為輸入流,若從程序內(nèi)部流到程序外部,則稱為輸出流;按照流數(shù)據(jù)處理的基本單位,可分為字節(jié)流和字符流,若流中數(shù)據(jù)的基本單位是字節(jié),則稱為字節(jié)流,若基本單位是字符,則稱為字符流;按照流功能的不同,可分為節(jié)點流和處理流,若流是直接從特定設(shè)備讀出的,例如從磁盤或者內(nèi)存讀出,那么叫做節(jié)點流,使用節(jié)點流作為輸入或者輸出的流叫做處理流,也叫過濾流,或者轉(zhuǎn)換流。 下面介紹幾種重要的輸入輸出流和Java提供的輸入輸出類。,9.1.2 字節(jié)流,InputStram和OutputStream是java.io包中定義的兩個抽象類,是所有字節(jié)流的父類。 InputS
3、tream類 InputStream是基本的輸入流類,它是一個抽象類,它定義了輸入流類共同的特性,是所有字節(jié)輸入流的父類,字節(jié)輸入流類的繼承關(guān)系如圖9.1所示。,InputStream類常用方法, OutputStream類,OutputStream是所有表示輸出流的父類,它是一個抽象類,它定義了輸出流類共同的特性,是鎖有字節(jié)輸出流的父類,OutputStream類常用方法, FileInputStream類,Java提供了專門的類對文件進(jìn)行輸入輸出操作。例如FileInputStream和FileOutputStream,這兩個類都屬于字節(jié)流,它們對數(shù)據(jù)進(jìn)行讀寫的基本單位是字節(jié)。 FileI
4、nputStream類是InputStream的子類,它實現(xiàn)了對文件的讀取,是文件字節(jié)輸入流。,FileInputStream類常用構(gòu)造方法, FileOutputStream類,FileOutputStream類是OnputStream的子類,它實現(xiàn)了對文件的寫入,是文件字節(jié)輸出流。,import java.io.*; class ReadWriteFile public static void main(String args) String file1,file2 ; int ch = 0 ; file1 =readme.txt ; file2=readme.bak; try FileI
5、nputStream fis = new FileInputStream(file1); FileOutputStream fos=new FileOutputStream(file2); int size=fis.available(); System.out.println(字節(jié)有效數(shù):+size); while (ch=fis.read()!=-1) System.out.write(ch); fos.write(ch); fis.close(); fos.close(); catch (IOException e) System.out.println(e.toString(); ,9
6、.1.3 字符流, Reader類 Reader類是所有字符輸入流的父類,提供了字符輸入流所有的基本功能,是所有字符輸入流的父類。,Reader類常用方法, Writer類,Writer是所有字符輸出流的父類,提供了字符輸出流的所有基本功能,是所有字符輸出流的父類 。,Writer類常用方法, InputStreamReader類,InputStreamReader類是字節(jié)流到字符流的轉(zhuǎn)換橋類,它可以根據(jù)指定的編碼方式,將字節(jié)輸入流轉(zhuǎn)換為字符輸入流。, OnputStreamWriter類,OnputStreamWriter類是字節(jié)流到字符流的轉(zhuǎn)換橋類,它可以根據(jù)指定的編碼方式,將字節(jié)輸出流轉(zhuǎn)
7、換為字符輸出流。,import java.io.*; public class StreamReaderWriterDemo public static void main(String args) try File file = new File(args0); FileInputStream fileInputStream = new FileInputStream(file); /為FileInputStream加上字符處理功能 InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); Fi
8、leOutputStream fileOutputStream = new FileOutputStream(backup_+args0); /為FileOutputStream加上字條處理功能 OutputStreamWriter outputStreamWriter= new OutputStreamWriter(fileOutputStream); int ch = 0; /以字符方式顯示文件內(nèi)容 while(ch = inputStreamReader.read() != -1) System.out.print(char) ch); outputStreamWriter.write(
9、ch); System.out.println(); inputStreamReader.close(); outputStreamWriter.close(); catch(ArrayIndexOutOfBoundsException e) System.out.println(沒有指定文件); catch(IOException e) e.printStackTrace(); , FileReader類,FileReader類是Reader類的子類,它實現(xiàn)了從文件中讀出字符數(shù)據(jù),是文件的字符輸入流。, FileWriter類,FileWriter類是Writer類的子類,它實現(xiàn)了將字符數(shù)據(jù)
10、寫入文件中,是文件的字符輸出流。,import java.io.*; class FileWriterDemo public static void main(String args) throws Exception String source = Now is the time for all good menn + to come to the aid of their countryn + and pay their due taxes.; char buffer = new charsource.length(); source.getChars(0, source.length()
11、, buffer, 0); FileWriter f0 = new FileWriter(file1.txt); for (int i=0; i buffer.length; i += 2) f0.write(bufferi); f0.close(); FileWriter f1 = new FileWriter(file2.txt); f1.write(buffer); f1.close(); FileWriter f2 = new FileWriter(file3.txt); f2.write(buffer,buffer.length-buffer.length/4,buffer.leng
12、th/4); f2.close(); , BufferedReader類,BufferedReader類是Reader類的子類,使用該類可以以行為單位讀取數(shù)據(jù)。, BufferedWriter類,BufferedWriter類是Writer類的子類,使用該類可以以行為單位寫入數(shù)據(jù)。,import java.util.*; import java.io.*; public class BufferedReaderWriterDemo public static void main(String args) try /緩沖System.in輸入流 /System.in是位流,可以通過InputSt
13、reamReader將其轉(zhuǎn)換為字符流 BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in); /緩沖FileWriter BufferedWriter bufWriter = new BufferedWriter(new FileWriter(args0); String input = null; /每讀一行進(jìn)行一次寫入動作 while(!(input = bufReader.readLine().equals(quit) bufWriter.write(input); /newLine(
14、)方法寫入與操作系統(tǒng)相依的換行字符,依執(zhí)行環(huán)境當(dāng)時的OS來決定該輸出那種換行字符 bufWriter.newLine(); bufReader.close(); bufWriter.close(); catch(ArrayIndexOutOfBoundsException e) System.out.println(沒有指定文件); catch(IOException e) e.printStackTrace(); , PrintWriter類,PrintWriter類是打印輸出流,該流把Java語言的內(nèi)構(gòu)類型以字符形式輸出到相應(yīng)的輸出流中,可以以文本方式瀏覽。,import java.io.
15、*; public class PrintWriterDemo public static void main(String args) throws FileNotFoundException String s; try BufferedReader in=new BufferedReader( new StringReader(ttt.txt); PrintWriter out=new PrintWriter( new BufferedWriter(new FileWriter(IODemo.out); int lineCount=1; while(s=in.readLine()!=nul
16、l ) out.println(lineCount+ + : + s); out.close(); catch(EOFException e) System.err.println(End of stream); catch(IOException e) e.printStackTrace(); ,9.1.4 過濾流,過濾器流是為某種目的過濾字節(jié)或字符的數(shù)據(jù)流?;据斎肓魈峁┑淖x取方法只能用來讀取字節(jié)或字符,而過濾器流能夠讀取整型、雙精度值和字符串,但需要一個過濾流類來包裝輸入流。 Java中定義了很多過濾流,例如BufferedOutputStream和BufferedInputStream
17、、 DataOutputStream和DataInputStream及PrintStream等。每一種過濾流都有自己適合使用的場所。, DataInputStream類,DataInputStream類是InputStream子類FilterInputStream的子類,實現(xiàn)DataInput接口,可以使一個應(yīng)用程序以與機器無關(guān)的方式從基本輸入流中讀取 Java 的基本數(shù)據(jù)類型。,DataInputStream類常用方法, DataOutputStream類,DataOutputStream類是OutputStream子類FilterOutputStream的子類,實現(xiàn)DataOnput接口,
18、可以使一個應(yīng)用程序以與機器無關(guān)的方式從基本輸入流中讀取 Java 的基本數(shù)據(jù)類型。,DataOutputStream類常用方法,import java.io.*; public class DataStreamDemo public static void main(String args) Member members = new Member(Justin,90), new Member(momor,95), new Member(Bush,88); try DataOutputStream dataOutputStream = new DataOutputStream(new FileO
19、utputStream(args0); for(Member member:members) dataOutputStream.writeUTF(member.getName();/寫入UTF字符串 dataOutputStream.writeInt(member.getAge(); /寫入int數(shù)據(jù) dataOutputStream.flush(); /所有數(shù)據(jù)至目的地 dataOutputStream.close(); /關(guān)閉流 DataInputStream dataInputStream = new DataInputStream(new FileInputStream(args0);
20、 /讀出數(shù)據(jù)并還原為對象 for(int i=0;imembers.length;i+) String name = dataInputStream.readUTF(); /讀出UTF字符串 int score = dataInputStream.readInt();/讀出int數(shù)據(jù) membersi = new Member(name,score); dataInputStream.close(); /關(guān)閉流 /顯示還原后的數(shù)據(jù) for(Member member : members) System.out.printf(%st%d%n,member.getName(),member.get
21、Age(); catch(IOException e) e.printStackTrace(); ,class Member private String name; private int age; public Member(String name, int age) = name; this.age = age; public void setName(String name) = name; public void setAge(int age) this.age = age; public String getName() return nam
22、e; public int getAge() return age; , BufferedInputStream類,BufferedInputStream類是InputStream子類FilterInputStream的子類,實現(xiàn)Closeable接口。作為另一種輸入流,創(chuàng)建 BufferedInputStream 時即創(chuàng)建了一個內(nèi)部緩沖區(qū)數(shù)組,可以在此緩沖區(qū)進(jìn)行數(shù)據(jù)操作。,BufferedInputStream類常用方法, BufferedOutputStream類,BufferedOutputStream類是OutputStream子類FilterOutputStream的子類,實現(xiàn)Clo
23、seable和Flushable接口。該類實現(xiàn)緩沖的輸出流。,BufferedOutputStream類常用方法,import java.io.*; public class BufferedStreamDemo public static void main(String args) try byte data = new byte1; File srcFile = new File(args0); File desFile = new File(args1); BufferedInputStream bufferedInputStream= new BufferedInputStream(
24、new FileInputStream(srcFile); BufferedOutputStream bufferedOutputStream= new BufferedOutputStream(new FileOutputStream(desFile); System.out.println(復(fù)制文件:+srcFile.length()+字節(jié)); while(bufferedInputStream.read(data)!=-1) bufferedOutputStream.write(data); /將緩沖區(qū)中的數(shù)據(jù)全部寫出 bufferedOutputStream.flush(); /關(guān)閉流
25、 bufferedInputStream.close(); bufferedOutputStream.close(); System.out.println(復(fù)制完成); catch(ArrayIndexOutOfBoundsException e) System.out.println(using:java UseFileStream src des); e.printStackTrace(); catch(IOException e) e.printStackTrace(); , PrintStream類,PrintStream類是打印輸出流,它可以直接輸出各種類型的數(shù)據(jù)。,import
26、java.io.*; public class PrintStreamDemo public static void main(String args) throws FileNotFoundException PrintStream printStream = new PrintStream(new FileOutputStream(new File(test.txt); printStream.println(1); printStream.close(); ,9.1.5 Java對文件的操作,Java提供File類、FileFilter接口、FilenameFilter接口和Random
27、AccessFile類對文件進(jìn)行操作。, File類,File類提供了對文件和文件夾進(jìn)行創(chuàng)建、刪除等基本操作。,File類的常用方法,import java.io.*; import java.util.Date; public class filetest public static void main(String args) String filename=e:javabook第1題.txt; File myfile=new File(filename); if(!myfile.exists() System.err.println(filename+未找到!); return; if(
28、 myfile.isDirectory() System.err.println(文件對象+myfile.getName()+是目錄!); File ds=new File(mydata); if(!ds.exists() ds.mkdir(); System.out.println(目錄+ds.getAbsolutePath()+創(chuàng)建結(jié)束!); return; if(myfile.isFile() System.out.println(文件對象:+myfile.getAbsolutePath(); System.out.println(文件字節(jié)數(shù):+myfile.length(); Syst
29、em.out.println(文件是否能讀:+myfile.canRead(); if(myfile.canWrite() System.out.println(設(shè)置文件為只讀:+myfile.setReadOnly(); System.out.println(文件是否可寫:+myfile.canWrite(); Date fd=new Date(myfile.lastModified(); System.out.println(文件上次修改時間:+fd.toString(); , FileFilter接口,FileFilter接口用于過濾抽象路徑名,此接口的實例可傳遞給File類的listF
30、iles(FileFilter)方法。, FilenameFilter接口,FilenameFilter接口用于過濾器抽象文件名。就像Windows經(jīng)常使用的打開文件窗口,可以通過其“文件類型”下拉列表查看當(dāng)前目錄下特定類型的文件。這種功能就是使用文件過濾器實現(xiàn)的。, RandomAccessFile類,使用RandomAccessFile類可以讀取文件任意位置的數(shù)據(jù),RandomAccessFile類有一個指針,用于確定文件讀寫的位置。RandomAccessFile類既不是輸入流的子類,也不是輸出流的子類,該類既可以進(jìn)行文件的輸入操作,也可以進(jìn)行文件的輸出操作。,RandomAccessF
31、ile類常用方法,import java.io.IOException; import java.io.File; import java.io.RandomAccessFile; public class RandomFileTest public static void main(String args) throws Exception Student s1=new Student(1, zhangsan, 90.5); Student s2=new Student(2, lisi, 98.5); Student s3=new Student(3, wangwu, 96.5); File
32、 userDir=new File(System.getProperties().getProperty(user.dir); File tempFile=File.createTempFile(student, .tmp, userDir); tempFile.deleteOnExit(); RandomAccessFile raf=new RandomAccessFile(tempFile, rw); s1.write(raf); s2.write(raf); s3.write(raf); raf.seek(0); Student s=new Student(); for(long i=0
33、;iraf.length();i=raf.getFilePointer() s.read(raf); System.out.println(lenth:+raf.length()+,i=+i+ + s); raf.close(); Thread.sleep(5000); ,class Student int num; String name; double score; public Student() public Student(int num, String name, double score) this.num=num; =name; this.score=score; public void write(RandomAccessFile raf) throws IOException raf.writeInt(num); raf.writeUTF(name); raf.writeDouble(score); public void
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年核輻射劑量防護(hù)儀器設(shè)備項目合作計劃書
- 2025年經(jīng)典心理健康知識競賽考試練習(xí)題庫(230題)【答案】
- 2024年鄧州市社區(qū)工作者招聘真題
- 2024年常德市市直中小學(xué)校招聘教師考試真題
- 項目管理制度規(guī)定
- 消防月消防知識題庫100道2
- 消防試題題庫4
- 2025年貿(mào)易經(jīng)紀(jì)與代理服務(wù)項目發(fā)展計劃
- 智慧城市發(fā)展中的數(shù)據(jù)隱私保護(hù)及IP管理策略探討
- 2025年油冷器項目發(fā)展計劃
- 成都市2022級(2025屆)高中畢業(yè)班摸底測試(零診)數(shù)學(xué)試卷(含答案)
- 社會主義核心價值觀融入幼兒園班級管理課程教學(xué)探索
- 《公平競爭審查條例》微課
- 四年級下冊混合計算400題及答案
- 餐廳值班管理培訓(xùn)
- OQC出貨檢驗技能培訓(xùn)
- 旅游產(chǎn)業(yè)行業(yè)分析
- 2024年四川成都市第八人民醫(yī)院人員招聘13人歷年高頻考題難、易錯點模擬試題(共500題)附帶答案詳解
- 社會工作倫理課件
- 胰腺癌術(shù)后護(hù)理查房課件
- 最全看圖猜成語 課件
評論
0/150
提交評論