第09章-文件輸入輸出ppt課件_第1頁
第09章-文件輸入輸出ppt課件_第2頁
第09章-文件輸入輸出ppt課件_第3頁
第09章-文件輸入輸出ppt課件_第4頁
第09章-文件輸入輸出ppt課件_第5頁
已閱讀5頁,還剩44頁未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

1、Java語言程序設(shè)計(jì)第九章 文件輸入輸出n概念nJava I/O類nJava I/O操作n標(biāo)準(zhǔn)輸入/輸出n文件讀寫操作n目錄管理n隨機(jī)訪問文件n文件屬性概念nI/O來源n控制臺(console, 如DOS窗口)打印/讀入n文件(file)讀/寫n網(wǎng)絡(luò)接口(TCP/UDP端口)讀/寫n針對數(shù)據(jù)的讀寫n以流(stream)的方式對數(shù)據(jù)進(jìn)行操作數(shù)據(jù)源程序讀出數(shù) 據(jù)流目的程序?qū)懭霐?shù) 據(jù)流流的重要特性順序讀/寫sequentially概念n讀/寫流的一般流程n讀(Reading)nopen a stream /打開讀出流nwhile more information /判斷n read informat

2、ion /讀nclose the stream /關(guān)閉流n寫(Writing)nopen a stream /打開寫入流nwhile more information /判斷n write information /寫nclose the stream /關(guān)閉流概念n兩種流的定義(讀取信息的基本數(shù)據(jù)單位)n字節(jié)流(byte stream): 一個(gè)字節(jié)(8-bit)一個(gè)字節(jié)讀/寫n字符流(character stream):一個(gè)字符一個(gè)字符讀/寫(具有特定字符編碼的數(shù)據(jù))j a v a 語 言6A 61 76 61 D3 EF D1 D4以字節(jié)流的方式讀: 讀8次,8個(gè)字節(jié)以字符流的方式讀: 讀

3、6次,6個(gè)字符第九章 文件輸入輸出n概念nJava I/O類nJava I/O操作n標(biāo)準(zhǔn)輸入/輸出n文件讀寫操作n目錄管理n隨機(jī)訪問文件n文件屬性Java I/O類n字節(jié)流的讀/寫操作(來自JDK1.0)njava.io.InputStream (抽象類)npublic abstract int read()npublic int read(byte b)npublic int read(byte b, int offset, int length)n到達(dá)流的終點(diǎn),無數(shù)據(jù)讀出則返回-1njava.io.OutputStream (抽象類)npublic abstract void write(

4、int b)npublic void write(byte b)npublic void write(byte b, int offset, int length) n所有的讀/寫函數(shù)都拋出java.io.IOExceptionJava I/O類n字符流的讀/寫操作(來自JDK1.1)njava.io.Reader (抽象類)npublic int read()npublic int read(char cbuf)npublc abstract int read(char cbuf, int offset, int length)n到達(dá)流的終點(diǎn),無數(shù)據(jù)讀出則返回-1njava.io.Write

5、r (抽象類)npublic void write(int c)npublic void write(char cbuf)npublic void write(char cbuf, int offset, int length)n所有的讀/寫函數(shù)都拋出java.io.IOExceptionJava I/O類nI/O流的層次關(guān)系nclass java.io.InputStream的子類nclass java.io.ByteArrayInputStreamnclass java.io.FileInputStreamnclass java.io.FilterInputStreamnclass jav

6、a.io.BufferedInputStreamnclass java.io.DataInputStream nclass java.io.LineNumberInputStreamnclass java.io.PushbackInputStreamnclass java.io.ObjectInputStream nclass java.io.PipedInputStreamnclass java.io.SequenceInputStreamnclass java.io.StringBufferInputStreamn Java I/O類nI/O流的層次關(guān)系nclass java.io.Out

7、putStream的子類nclass java.io.ByteArrayOutputStreamnclass java.io.FileOutputStreamnclass java.io.FilterOutputStreamnclass java.io.BufferedOutputStreamnclass java.io.DataOutputStream nclass java.io.PrintStreamnclass java.io.ObjectOutputStreamnclass java.io.PipedOutputStreamn Java I/O類nI/O流的層次關(guān)系nclass ja

8、va.io.Reader的子類nclass java.io.BufferedReadernclass java.io.LineNumberReadernclass java.io.CharArrayReadernclass java.io.FilterReader nclass java.io.PushbackReadernclass java.io.InputStreamReadernclass java.io.FileReadernclass java.io.PipedReadernclass java.io.StringReadern Java I/O類nI/O流的層次關(guān)系nclass

9、java.io.Writer的子類nclass java.io.BufferedWriternclass java.io.CharArrayWriternclass java.io.FilterWriternclass java.io.OutputStreamWriter nclass java.io.FileWriternclass java.io.PipedWriternclass java.io.PrintWriternclass java.io.StringWritern Java I/O類nI/O流的分類 (12個(gè)功能類)I/O類型所用到的類描述文件FileReader/FileWr

10、iterFileInputStream/FileOutputStream文件流(讀/寫文件)緩沖BufferedReader/BufferedWriterBufferedInputStreamBufferedOutputStream提高讀/寫效率打印PrintWriter PrintStream (System.out.println()內(nèi)存CharArrayReader/CharArrayWriterByteArrayInputStreamByteArrayOutputStreamStringReader/StringWriterStringBufferInputStream讀/寫內(nèi)存Jav

11、a I/O類nI/O流的分類 (12個(gè)功能類)I/O類型所用到的類描述字節(jié)流和字符流的轉(zhuǎn)換InputStreamReaderOutputStreamWriter將InputStream中讀入的字節(jié)轉(zhuǎn)為字符/將字符轉(zhuǎn)為字節(jié)寫入OutputStream管道pipePipedReader/PipedWriterPipedInputStream/PipedOutputStream文件流(讀/寫文件)連接ConcatenationSequenceInputStream多個(gè)輸入流連接為一個(gè)輸入流對象串行化ObjectInputStreamObjectOutputStreamObject Serializa

12、tionJava I/O類nI/O流的分類 (12個(gè)功能類)I/O類型所用到的類描述基本數(shù)據(jù)轉(zhuǎn)化DataInputStreamDataOutputStreamJAVA基本數(shù)據(jù)類型的讀/寫計(jì)數(shù)LineNumberReaderLineNumberInputStream讀操作時(shí)記錄行數(shù)Peeking AheadPushbackReaderPushbackInputStream可回退緩存(pushback buffer)過濾FilterReader/FilterWriterFilterInputStream/FilterOutputStream在讀/寫操作時(shí)對數(shù)據(jù)進(jìn)行過濾第九章 文件輸入輸出n概念nJ

13、ava I/O類nJava I/O操作n標(biāo)準(zhǔn)輸入/輸出n文件讀寫操作n目錄管理n隨機(jī)訪問文件n文件屬性Java I/O操作n主要內(nèi)容n標(biāo)準(zhǔn)輸入/輸出n控制臺屏幕打印和鍵盤讀入n文件I/O操作n文件讀寫n如何提高文件讀寫效率n流的包裝(Wrap)n基本數(shù)據(jù)轉(zhuǎn)換流n目錄管理n隨機(jī)訪問文件(Random Access File)n文件屬性n網(wǎng)絡(luò)流操作(見第十三講)n輸出: 控制臺屏幕打印nclass Test npublic static void main(String args) nSystem.out.println(“Hello World!”);nn標(biāo)準(zhǔn)輸入/輸出n輸入: 鍵盤讀入nimp

14、ort java.io.IOException;nclass Test npublic static void main(String args) throwsn IOException nbyte b = new byte10;nSystem.out.println(Received number= +n System.in.read(b);nn標(biāo)準(zhǔn)輸入/輸出C:java TestAReceived number=3C:n文件讀/寫流程n打開文件流n條件判斷n讀出/寫入n關(guān)閉文件流n兩種類型文件nFileInputStream/FileOutputStream (字節(jié)流)nFileReade

15、r/FileWriter (字符流)文件讀寫操作n字節(jié)流構(gòu)造方法npublic FileInputStream(File file) throws FileNotFoundExceptionnpublic FileInputStream(String name) throws FileNotFoundExceptionnpublic File(String pathname)npublic FileOutputStream(File file) throws FileNotFoundExceptionnpublic FileOutputStream(File file, boolean app

16、end) throws FileNotFoundException /是否向已存在的文件后添加npublic FileOutputStream(String name) throws FileNotFoundExceptionnpublic FileOutputStream(String name, boolean append) throws FileNotFoundException文件讀寫操作n文件讀寫-實(shí)例1文件讀寫操作import java.io.*;public class CopyBytes public static void main(String args) throws

17、IOException File inputFile = new File(“original.txt); File outputFile = new File(“result.txt); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while (c = in.read() != -1) out.write(c); in.close(); out.close(); public int read ()thr

18、ows IOExceptionpublic int read (byte b) throws IOExceptionpublic int read (byte b, int off, int len) throws IOExceptionFileInputStream in = new FileInputStream(“original.txt);FileOutputStream out = new FileOutputStream(“result.txt);public void write (int b) throws IOExceptionpublic void write (byte

19、b) throws IOExceptionpublic void write (byte b, int off, int len) throws IOExceptionn字符流構(gòu)造方法npublic FileReader(File file) throws FileNotFoundExceptionnpublic FileReader(String fileName) throws FileNotFoundExceptionnpublic File(String pathname)npublic FileWriter(File file) throws IOExceptionnpublic F

20、ileWriter(File file, boolean append) throws IOExceptionnpublic FileWriter(String fileName) throws IOExceptionnpublic FileWriter(String fileName, boolean append) throws IOException文件讀寫操作n文件讀寫-實(shí)例2文件讀寫操作import java.io.*;public class Copy public static void main(String args) throws IOException File inpu

21、tFile = new File(“original.txt); File outputFile = new File(“result.txt); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while (c = in.read() != -1) out.write(c); in.close(); out.close(); FileReader in = new FileReader(“original.txt);FileWriter out = n

22、ew FileWriter(“result.txt);public int read () throws IOExceptionpublic int read (char cbuf) throws IOExceptionpublic int read (char cbuf, int off, int len) throws IOExceptionpublic void write (int b) throws IOExceptionpublic void write (char cbuf) throws IOExceptionpublic void write (char cbuf, int

23、off, int len) throws IOExceptionn兩類緩沖流n針對字節(jié)流njava.io.BufferedInputStream類njava.io.BufferedOutputStream類n針對字符流njava.io.BufferedReader類njava.io.BufferedWriter類如何提高文件讀寫效率n構(gòu)造方法npublic BufferedInputStream(InputStream in) 2048 bytesnpublic BufferedInputStream(InputStream in, int size)npublic BufferedOutpu

24、tStream(OutputStream out) 512 bytesnpublic BufferedOutputStream(OutputStream out, int size)npublic BufferedReader(Reader in) 8192 bytesnpublic BufferedReader(Reader in, int sz)npublic BufferedWriter(Writer out) 8192 bytenpublic BufferedWriter(Writer out, int sz)如何提高文件讀寫效率 String filename = “test.txt

25、”; FileInputStream fis = new FileInputStream(filename); int count = 0; int c; while (c = fis.read() != -1) if (c = A) count+; fis.close(); System.out.println(count);n如何提高文件讀寫效率-實(shí)例1如何提高文件讀寫效率 String filename = “test.txt”; FileInputStream fis = new FileInputStream(filename); BufferedInputStream bis =

26、new BufferedInputStream(fis); int count = 0; int c; while (c = bis.read() != -1) if (c = A) count+; fis.close(); System.out.println(count); FileInputStream fis = new FileInputStream(“test.txt”); int count = 0; final int BUFSIZE = 1024; byte buf = new byteBUFSIZE; int len; while (len = fis.read(buf)

27、!= -1) for (int i = 0; i len; i+) if (bufi = A) count+; fis.close(); String filename = “test.txt”; FileReader fr = new FileReader(filename); BufferedReader br = new BufferedReader(fr); int count = 0; while (br.readLine() != null) count+; br.close(); System.out.println(count);n如何提高文件讀寫效率-實(shí)例2如何提高文件讀寫效

28、率n概述流的包裝(wrap) FileReader fr = new FileReader (filename); BufferedReader br = new BufferedReader (fr); BufferedReader br = new BufferedReader ( new FileReader(filename); PrintWriter out = new PrintWriter ( new BufferedWriter(new FileWriter(filename); public String readLine() in java.io.BufferedReade

29、r public void println(String x) in java.io.PrintWritern利用不同流的特點(diǎn)(方法)n尋找合適的方法完成特定的需求n對已有的流進(jìn)行再處理n流的種類n節(jié)點(diǎn)流n直接對數(shù)據(jù)源進(jìn)行讀/寫操作的流n處理流n對一個(gè)已有的流進(jìn)行某種操作的流流的包裝(wrap)n節(jié)點(diǎn)流nFileInputStream, PipedInputStream, ByteArrayInputStream, StringBufferInputStreamnFileOutputStream, PipedOutputStream, ByteArrayOutputStreamnCharArr

30、ayReader, FileReader, PipedReader, StringReadernCharArrayWriter, FileWriter, PipedWriter, StringWriter流的包裝(wrap)n處理流nFilterOutputStream, DataOutputStream, BufferedOutputStream, PrintStreamnFilterInputStream, LineNumberInputStream, DataInputStream, BufferedInputStream, PushbackInputStreamnBufferedRea

31、der, LineNumberReader, InputStreamReader, FilterReader, PushBackReadernBufferedWriter, OutputStreamReader, FilterWriter, PrintWriter流的包裝(wrap)n一個(gè)實(shí)例njava.io.FileReadernpublic FileReader(File file) throws FileNotFoundExceptionnpublic FileReader(String fileName) throws FileNotFoundExceptionnjava.io.Buf

32、feredReadernpublic BufferedReader(Reader in) 8192 bytesnpublic BufferedReader(Reader in, int sz)n流的包裝改變了流的行為流的包裝(wrap)n流的包裝(wrap)-實(shí)例1流的包裝(wrap)import java.io.*;public class Echo public static void main(String args) throws IOException BufferedReader in = new BufferedReader( new InputStreamReader(Syst

33、em.in); String s; while(s = in.readLine().length() != 0) System.out.println(s); public static final InputStream in (java.lang.System)public InputStreamReader(InputStream in)public BufferedReader(Reader in)程序如何結(jié)束(跳出while循環(huán))?n概述njava.io.DataInputStream類npublic DataInputStream(InputStream in)npublic fi

34、nal boolean readBoolean()npublic final byte readByte()npublic final char readChar()npublic final int readInt()njava.io.DataOutputStream類npublic DataOutputStream(OutputStream out)npublic final void writeBoolean(boolean v)npublic final void writeByte(int v)npublic final void writeChar(int v)npublic fi

35、nal void writeInt(int v)基本數(shù)據(jù)轉(zhuǎn)換流DataOutputStream out = new DataOutputStream(new FileOutputStream(invoice1.txt);double prices = 19.99, 9.99;int units= 12, 8;String descs = Java T-shirt, Java Mug;for (int i = 0; i prices.length; i +) out.writeDouble(pricesi);out.writeChar(t);out.writeInt(unitsi);out.wr

36、iteChar(t);out.writeChars(descsi);out.writeChar(n);out.close();n基本數(shù)據(jù)轉(zhuǎn)換流-實(shí)例基本數(shù)據(jù)轉(zhuǎn)換流DataInputStream in = new DataInputStream( new FileInputStream(invoice1.txt);double total;try while (true) double price = in.readDouble(); in.readChar(); int unit = in.readInt(); in.readChar(); char chr; StringBuffer des

37、c = new StringBuffer(20);while (chr = in.readChar()!= n) desc.append(chr);System.out.println(Youve ordered + unit + units of + desc + at $ + price); total = total + unit * price; catch (EOFException e) System.out.println(For a TOTAL of: $ + total);in.close();19.99 12 Java T-shirt9.99 8 Java Mug n概述n

38、java.io.File類: 文件和目錄的路徑名n構(gòu)造方法npublic File(String pathname)npublic File(String parent, String child)npublic File(File parent, String child)nparent通常表示一個(gè)目錄, child則表示一個(gè)目錄或文件n路徑名(pathname)nUNIX平臺上絕對路徑的前綴“/”,相對路徑無前綴,例“/etc/inetd.conf”、“inetd.conf”nWindows平臺,絕對路徑名的前綴由“盤符:”組成;UNC 路徑名前綴為“”,然后是主機(jī)名和共享名,相對路徑名無

39、盤符,例“c:windowsnotepad.exe”、“notepad.exe”目錄管理n方法npublic boolean canWrite()/canRead()npublic boolean exists()npublic boolean delete() 刪除文件或目錄,若刪除目錄,要求該目錄必須為空npublic boolean createNewFile() 創(chuàng)建一個(gè)空文件,當(dāng)且僅當(dāng)該文件不存在npublic boolean isDirectory()/isFile()/isHidden()npublic long lastModified()/public boolean set

40、LastModified(long time)npublic String list() 得到當(dāng)前目錄下的所有文件名和目錄名,若該File對象不是表示目錄,則返回nullnpublic boolean mkdir()/mkdirs() 創(chuàng)建一個(gè)目錄npublic boolean renameTo(File dest)npublic boolean setReadOnly()目錄管理n目錄管理方法舉例目錄管理import java.io.File;public class DirList public static void main(String args) File path = new F

41、ile(.);String list = path.list();for(int i = 0; i list.length; i+)System.out.println(listi);n目錄管理方法舉例目錄管理import java.io.File;import java.io.FilenameFilter;public class DirList public static void main(String args) File path = new File(.);String list = path.list(new DirFilter(args0); for (int i = 0; i

42、 list.length; i+) System.out.println(listi);class DirFilter implements FilenameFilter String key; DirFilter(String key) this.key = key; public boolean accept(File dir, String name) String f = new File(name).getName();return f.indexOf(key) != -1; java.util.FilenameFilter 接口 public boolean accept(File

43、 dir, String name); /是否指定的文件應(yīng)包含在文件列表中public String getName() in java.io.File/獲得文件或目錄名,僅僅是最后的部分n隨機(jī)訪問文件(Random Access File)njava.io.RandomAccessFile類n讀寫操作在同一個(gè)類中完成,須在構(gòu)造對象時(shí)指定參數(shù)n通過移動(dòng)文件指針(file pointer)在文件的指定位置進(jìn)行讀寫操作n構(gòu)造方法npublic RandomAccessFile(String name, String mode) throws FileNotFoundExceptionnpublic

44、 RandomAccessFile(File file, String mode) throws FileNotFoundExceptionnmode: “r”, “rw”隨機(jī)訪問文件n方法npublic void seek(long pos) npublic int read()npublic int read(byte b)npublic int read(byte b, int off, int len)npublic final boolean readBoolean()/readByte()/readChar()/readShort()/readInt()/readDouble()/

45、readFloat()npublic final String readLine()npublic void write(int b)npublic void write(byte b)npublic void write(byte b, int off, int len)npublic final void writeBoolean()/writeByte()/writeChar()/writeShort()/writeInt()/writeDouble()/writeFloat()隨機(jī)訪問文件n隨機(jī)訪問文件(Random Access File)-實(shí)例隨機(jī)訪問文件RandomAccessF

46、ile rf = new RandomAccessFile(rtest.dat, rw);for(int i = 0; i 10; i+)rf.writeDouble(i*1.414);rf.close();rf = new RandomAccessFile(rtest.dat, rw);rf.seek(5*8);rf.writeDouble(47.0001);rf.close();rf = new RandomAccessFile(rtest.dat, r);for(int i = 0; i 10; i+)System.out.println(Value + i + : + rf.readD

47、ouble();rf.close();運(yùn)行結(jié)果:Value 0: 0.0Value 1: 1.414Value 2: 2.828Value 3: 4.242Value 4: 5.656Value 5: 47.0001Value 6: 8.484Value 7: 9.898Value 8: 11.312Value 9: 12.725999999999999n文件的特性n讀和寫的權(quán)限n文件長度n修改時(shí)間n是否是目錄njava.io.File類n設(shè)定文件屬性n查詢文件屬性文件屬性文件屬性n獲取文件路徑import java.io.*;class AttrDemo1 public static void main(String args) throws IOException File testfile = new File(. + File.separatorChar + testfile1); t

溫馨提示

  • 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)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論