版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領
文檔簡介
1、畢業(yè)設計(論文)外文文獻翻譯譯文:Java I/O 系統(tǒng)對編程語言的設計者來說,創(chuàng)建一套好的輸入輸出(I/O)系統(tǒng),是一項難度極高的任務。這一類可以從解決方案的數(shù)量之多上看出端倪。這個問題就難在它要面對的可能性太多了。不僅是因為有那么多的I/O的源和目的(文件,控制臺,網(wǎng)絡連接等等),而且還有很多方法(順序的,隨機的,緩存的,二進制的,字符方式的,行的,字的等等)。Java類庫的設計者們用“創(chuàng)建很多類”的辦法來解決這個問題。坦率地說,Java I/O系統(tǒng)的類實在太多了,以至于初看起來會把人嚇著(但是,具有諷刺意味的是,這種設計實際上是限制了類的爆炸性增長)。此外,Java在1.0版之后又對其I
2、/O類庫進行了重大的修改,原先是面向byte的,現(xiàn)在又補充了面向Unicode字符的類庫。為了提高性能,完善功能,JDK1.4又加了一個nio(意思是“new I/O”。這個名字會用上很多年)。這么以來,如果你想對Java 的I/O類庫有個全面了解,并且做到運用自如,你就得先學習大量的類。此外,了解I/O類庫的演化歷史也是相當重要的??赡苣愕牡谝环磻恰皠e拿什么歷史來煩我了,告訴我怎么用就可以了!”但問題是,如果你對這段一無所知,很快就會被一些有用或是沒用的類給搞糊涂了。本文會介紹Java 標準類庫中的各種I/O類,及其使用方法。File 類在介紹直接從流里讀寫數(shù)據(jù)的類之前,我們先介紹一下處理
3、文件和目錄的類。你會認為這是一個關于文件的類,但它不是。你可以用它來表示某個文件的名字,也可以用它來表示目錄里一組文件的名字。如果它表示的是一組文件,那么你還可以用list( )方法來進行查詢,讓它會返回String數(shù)組。由于元素數(shù)量是固定的,因此數(shù)組會比容器更好一些。如果你想要獲取另一個目錄的清單,再建一個File對象就是了。 目錄列表器假設你想看看這個目錄。有兩個辦法。一是不帶參數(shù)調(diào)用list( )。它返回的是File對象所含內(nèi)容的完整清單。但是,如果你要的是一個限制性列表(restricted list)的話 比方說,你想看看所有擴展名為.java的文件 那么你就得使用目錄過濾器了。這是
4、一個專門負責挑選顯示File對象的內(nèi)容的類。 FilenameFilter接口的聲明: public interface FilenameFilter boolean accept(File dir, String name);accept( )方法需要兩個參數(shù),一個是File對象,表示這個文件是在哪個目錄里面的;另一個是String,表示文件名。雖然你可以忽略它們中的一個,甚至兩個都不管,但是你大概總得用一下文件名吧。記住,list( )會對目錄里的每個文件調(diào)用accept( ),并以此判斷是不是把它包括到返回值里;這個判斷依據(jù)就是accept( )的返回值。 切記,文件名里不能有路徑信息。
5、為此你只要用一個String對象來創(chuàng)建File對象,然后再調(diào)用這個File對象的getName( )就可以了。它會幫你剝離路徑信息(以一種平臺無關的方式)。然后再在accept( )里面用正則表達式(regular expression)的matcher對象判斷,regex是否與文件名相匹配。兜完這個圈子,list( )方法返回了一個數(shù)組。 匿名內(nèi)部類這是用匿名內(nèi)部類來征程程序的絕佳機會。下面我們先創(chuàng)建一個返回FilenameFileter的filter()方法。/ Uses anonymous inner classes.import java.io.*;import java.util.*
6、;import com.bruceeckel.util.*;public class DirList2 public static FilenameFilter filter(final String afn) / Creation of anonymous inner class: return new FilenameFilter() String fn = afn; public boolean accept(File dir, String n) / Strip path information: String f = new File(n).getName(); return f.i
7、ndexOf(fn) != -1; ; / End of anonymous inner class public static void main(String args) File path = new File(.); String list; if(args.length = 0) list = path.list(); else list = path.list(filter(args0); Arrays.sort(list, new AlphabeticComparator(); for(int i = 0; i list.length; i+) System.out.printl
8、n(listi); 注意,filter( )的參數(shù)必須是final的。要想在匿名內(nèi)部類里使用其作用域之外的對象,只能這么做。這是對前面所講的代碼的改進,現(xiàn)在FilenameFilter類已經(jīng)與DirList2緊緊地綁在一起了。不過你還可以更進一步,把這個匿名內(nèi)部類定義成list()的參數(shù),這樣代碼會變得更緊湊:/ Building the anonymous inner class in-place.import java.io.*;import java.util.*;import com.bruceeckel.util.*;public class DirList3 public stat
9、ic void main(final String args) File path = new File(.); String list; if(args.length = 0) list = path.list(); else list = path.list(new FilenameFilter() public boolean accept(File dir, String n) String f = new File(n).getName(); return f.indexOf(args0) != -1; ); Arrays.sort(list, new AlphabeticCompa
10、rator(); for(int i = 0; i list.length; i+) System.out.println(listi); 現(xiàn)在該輪到main()的參數(shù)成final了,因為匿名內(nèi)部類要用它的arg0.這個例子告訴我們,可以用匿名內(nèi)部類來創(chuàng)建專門供特定問題用的,一次性的類。這種做法的好處是,它能把解決某個問題的代碼全部集中到一個地方。但是從另一角度來說,這樣做會使代碼的可讀性變差,所以要慎重。查看與創(chuàng)建目錄File類的功能不僅限于顯示文件或目錄。它還能幫你創(chuàng)建新的目錄甚至是目錄路徑(directorypath),如果目錄不存在的話。此外它還能用來檢查文件的屬性(大小,上次修改的日
11、期,讀寫權限等),判斷File對象表示的是文件還是目錄,以及刪除文件。 renameTo( )這個方法會把文件重命名成(或者說移動到)新的目錄,也就是參數(shù)所給出的目錄。而參數(shù)本身就是一個File對象。這個方法也適用于目錄。輸入與輸出I/O類庫常使用流(stream)這種抽象。所謂流是一種能生成或接受數(shù)據(jù)的,代表數(shù)據(jù)的源和目標的對象。流把I/O設備內(nèi)部的具體操作給隱藏起來了。 正如JDK文檔所示的,Java的I/O類庫分成輸入和輸出兩大部分。所有InputStream和Reader的派生類都有一個基本的,繼承下來的,能讀取單個或byte數(shù)組的read( )方法。同理,所有OutputStream
12、和Writer的派生類都有一個基本的,能寫入單個或byte數(shù)組的write( )方法。但通常情況下,你是不會去用這些方法的;它們是給其它類用的 而后者會提供一些更實用的接口。因此,你很少會碰到只用一個類就能創(chuàng)建一個流的情形,實際上你得把多個對象疊起來,并以此來獲取所需的功能。Java的流類庫之所以會那么讓人犯暈,最主要的原因就是你必須為創(chuàng)建一個流而動用多個對象。 我們最好還是根據(jù)其功能為這些class歸個類。Java 1.0 的類庫設計者們是從決定“讓所有與輸入相關的類去繼承InputStream”入手的。同理,所有與輸出相關的類就該繼承OutputStream了。添加屬性與適用的接口使用分層
13、對象(layered objects),為單個對象動態(tài)地,透明地添加功能的做法,被稱為DecoratorPattern。(模式是Thinkingin Patterns (with Java)的主題。)Decorator模式要求所有包覆在原始對象之外的對象,都必須具有與之完全相同的接口。這使得decorator的用法變得非常的透明-無論對象是否被decorate過,傳給它的消息總是相同的。這也是Java I/O類庫要有filter(過濾器)類的原因:抽象的filter類是所有decorator的基類。(decorator必須具有與它要包裝的對象的全部接口,但是decorator可以擴展這個接口,
14、由此就衍生出了很多filter類)。 Decorator模式常用于如下的情形:如果用繼承來解決各種需求的話,類的數(shù)量會多到不切實際的地步。Java的I/O類庫需要提供很多功能的組合,于是decorator模式就有了用武之地。但是decorator有個缺點,在提高編程的靈活性的同時(因為你能很容易地混合和匹配屬性),也使代碼變得更復雜了。Java的I/O類庫之所以會這么怪,就是因為它必須為一個I/O對象創(chuàng)建很多類,也就是為一個核心I/O類加上很多decorator。 為InputStream和OutputStream定義decorator類接口的類,分別是FilterInputStream和Fi
15、lterOutputStream。這兩個名字都起得不怎么樣。FilterInputStream和FilterOutputStream都繼承自I/O類庫的基類InputStream和OutputStream,這是decorator模式的關鍵(惟有這樣decorator類的接口才能與它要服務的對象的完全相同)。 用FilterInputStream讀取InputStreamFilterInputStream及其派生類有兩項重要任務。DataInputStream可以讀取各種primitive及String。(所有的方法都以read打頭,比如readByte( ), readFloat( )。它,以
16、及它的搭檔DataOutputStream,能讓你通過流將primitive數(shù)據(jù)從一個地方導到另一個地方。這些地方都列在表12-4里。 其它的類都是用來修改InputStream的內(nèi)部行為的:是不是做緩沖,是不是知道它所讀取的行信息(允許你讀取行號或設定行號),是不是會彈出單個字符。后兩個看上去更像是給編譯器用的(也就是說,它們大概是為Java編譯器設計的),所以通常情況下,你是不大會用到它們的。 不論你用哪種I/O設備,輸入的時候,最好都做緩沖。所以對I/O類庫來說,比較明智的做法還是把不緩沖當特例(或者去直接調(diào)用方法),而不是像現(xiàn)在這樣把緩沖當作特例。外文原文:JAVA I/O Syste
17、mCreating a good input/output (I/O) system is one of the more difficult tasks for the language designer.This is evidenced by the number of different approaches. The challenge seems to be in covering all eventualities. Not only are there different sources and sinks of I/O that you want to communicate
18、 with (files, the console, network connections), but you need to talk to them in a wide variety of ways (sequential, random-access, buffered, binary, character, by lines, by words, etc.).The Java library designers attacked this problem by creating lots of classes. In fact, there are so many classes
19、for Javas I/O system that it can be intimidating at first (ironically, the Java I/O design actually prevents an explosion of classes). There was also a significant change in the I/O library after Java 1.0, when the original byte-oriented library was supplemented with char-oriented, Unicode-based I/O
20、 classes. As a result there are a fair number of classes to learn before you understand enough of Javas I/O picture that you can use it properly. In addition, its rather important to understand the evolution history of the I/O library, even if your first reaction is “dont bother me with history, jus
21、t show me how to use it!” The problem is that without the historical perspective you will rapidly become confused with some of the classes and when you should and shouldnt use them. This article will give you an introduction to the variety of I/O classes in the standard Java library and how to use t
22、hem. The File classBefore getting into the classes that actually read and write data to streams, well look a utility provided with the library to assist you in handling file directory issues. The File class has a deceiving nameyou might think it refers to a file, but it doesnt. It can represent eith
23、er the name of a particular file or the names of a set of files in a directory. If its a set of files, you can ask for the set with the list() method, and this returns an array of String. It makes sense to return an array rather than one of the flexible container classes because the number of elemen
24、ts is fixed, and if you want a different directory listing you just create a different File object. In fact, “FilePath” would have been a better name for the class. This section shows an example of the use of this class, including the associated FilenameFilter interface. A directory listerSuppose yo
25、ud like to see a directory listing. The File object can be listed in two ways. If you call list() with no arguments, youll get the full list that the File object contains. However, if you want a restricted listfor example, if you want all of the files with an extension of .javathen you use a “direct
26、ory filter,” which is a class that tells how to select the File objects for display. The DirFilter class “implements” the interface FilenameFilter. Its useful to see how simple the FilenameFilter interface is: public interface FilenameFilter boolean accept(File dir, String name);The accept() method
27、must accept a File object representing the directory that a particular file is found in, and a String containing the name of that file. You might choose to use or ignore either of these arguments, but you will probably at least use the file name. Remember that the list() method is calling accept() f
28、or each of the file names in the directory object to see which one should be includedthis is indicated by the boolean result returned by accept(). To make sure the element youre working with is only the file name and contains no path information, all you have to do is take the String object and crea
29、te a File object out of it, then call getName(), which strips away all the path information (in a platform-independent way). Then accept() uses the a regular expression matcher object to see if the regular expression regex matches the name of the file.Using accept(),the list()method returns an array
30、.Anonymous inner classesThis example is ideal for rewriting using an anonymous inner class. As a first cut, a method filter() is created that returns a reference to a FilenameFilter:/ Uses anonymous inner classes.import java.io.*;import java.util.*;import com.bruceeckel.util.*;public class DirList2
31、public static FilenameFilter filter(final String afn) / Creation of anonymous inner class: return new FilenameFilter() String fn = afn; public boolean accept(File dir, String n) / Strip path information: String f = new File(n).getName(); return f.indexOf(fn) != -1; ; / End of anonymous inner class p
32、ublic static void main(String args) File path = new File(.); String list; if(args.length = 0) list = path.list(); else list = path.list(filter(args0); Arrays.sort(list, new AlphabeticComparator(); for(int i = 0; i list.length; i+) System.out.println(listi); Note that the argument to filter() must be
33、 final. This is required by the anonymous inner class so that it can use an object from outside its scope. This design is an improvement because the FilenameFilter class is now tightly bound to DirList2. However, you can take this approach one step further and define the anonymous inner class as an
34、argument to list(), in which case its even smaller:/ Building the anonymous inner class in-place.import java.io.*;import java.util.*;import com.bruceeckel.util.*;public class DirList3 public static void main(final String args) File path = new File(.); String list; if(args.length = 0) list = path.lis
35、t(); else list = path.list(new FilenameFilter() public boolean accept(File dir, String n) String f = new File(n).getName(); return f.indexOf(args0) != -1; ); Arrays.sort(list, new AlphabeticComparator(); for(int i = 0; i list.length; i+) System.out.println(listi); The argument to main() is now final
36、, since the anonymous inner class uses args0 directly. This shows you how anonymous inner classes allow the creation of quick-and-dirty classes to solve problems. Since everything in Java revolves around classes, this can be a useful coding technique. One benefit is that it keeps the code that solve
37、s a particular problem isolated together in one spot. On the other hand, it is not always as easy to read, so you must use it judiciously. Checking for and creating directoriesThe File class is more than just a representation for an existing file or directory. You can also use a File object to creat
38、e a new directory or an entire directory path if it doesnt exist. You can also look at the characteristics of files (size, last modification date, read/write), see whether a File object represents a file or a directory, and delete a file. The first method thats exercised by main() is renameTo(), whi
39、ch allows you to rename (or move) a file to an entirely new path represented by the argument, which is another File object. This also works with directories of any length. Input and outputI/O libraries often use the abstraction of a stream, which represents any data source or sink as an object capab
40、le of producing or receiving pieces of data. The stream hides the details of what happens to the data inside the actual I/O device. The Java library classes for I/O are divided by input and output, as you can see by looking at the online Java class hierarchy in the JDK documentation. By inheritance,
41、 everything derived from the InputStream or Reader classes have basic methods called read() for reading a single byte or array of bytes. Likewise, everything derived from OutputStream or Writer classes have basic methods called write() for writing a single byte or array of bytes. However, you wont g
42、enerally use these methods; they exist so that other classes can use themthese other classes provide a more useful interface. Thus, youll rarely create your stream object by using a single class, but instead will layer multiple objects together to provide your desired functionality. The fact that yo
43、u create more than one object to create a single resulting stream is the primary reason that Javas stream library is confusing. Its helpful to categorize the classes by their functionality. In Java 1.0, the library designers started by deciding that all classes that had anything to do with input wou
44、ld be inherited from InputStream and all classes that were associated with output would be inherited from OutputStream. Adding attributes and useful interfacesThe use of layered objects to dynamically and transparently add responsibilities to individual objects is referred to as the Decorator patter
45、n. The decorator pattern specifies that all objects that wrap around your initial object have the same interface. This makes the basic use of the decorators transparentyou send the same message to an object whether its been decorated or not. This is the reason for the existence of the “filter” class
46、es in the Java I/O library: the abstract “filter” class is the base class for all the decorators. (A decorator must have the same interface as the object it decorates, but the decorator can also extend the interface, which occurs in several of the “filter” classes). Decorators are often used when si
47、mple subclassing results in a large number of subclasses in order to satisfy every possible combination that is neededso many subclasses that it becomes impractical. The Java I/O library requires many different combinations of features, which is why the decorator pattern is used. There is a drawback
48、 to the decorator pattern, however. Decorators give you much more flexibility while youre writing a program (since you can easily mix and match attributes), but they add complexity to your code. The reason that the Java I/O library is awkward to use is that you must create many classesthe “core” I/O type plus all the decoratorsin order to get the single I/O object that you want. The classes that provide the decorator interface to control a particular InputStream or OutputS
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 二零二五年度建筑工地臨時用工人員工資支付與爭議調(diào)解協(xié)議3篇
- 應急管理概論 教學大綱
- 企業(yè)流程管理培訓
- 二零二五年度廣告銷售渠道拓展合同范本3篇
- ChatGPT助推學校教育數(shù)字化轉型-人工智能時代學什么與怎么教
- 航空母艦發(fā)展史
- 炒菜放料知識培訓課件
- 山西省朔州市懷仁市2024-2025學年七年級上學期1月期末生物試題(無答案)
- Unit6 Shopping A let's spell (說課稿)-2023-2024學年人教PEP版英語四年級下冊
- 第16章 分式 評估測試卷(含答案)2024-2025學年數(shù)學華東師大版八年級下冊
- 2024年國家公務員考試《行測》真題(行政執(zhí)法)
- 煙花爆竹安全生產(chǎn)管理人員考試題庫附答案(新)
- 國有企業(yè)外派董監(jiān)事、高管人員管理辦法
- 2024年個人汽車抵押借款合同范本(四篇)
- 春聯(lián)課件教學課件
- 北師大版五年級上冊脫式計算400道及答案
- 安徽省蕪湖市2023-2024學年高一上學期期末考試 地理試題
- 8《美麗文字 民族瑰寶》教學設計2023-2024學年統(tǒng)編版道德與法治五年級上冊
- 2024年工業(yè)廢水處理工(初級)技能鑒定考試題庫(含答案)
- 2024新滬教版英語初一上單詞表(英譯漢)
- 人教版八年級上冊生物期末必刷15道識圖題
評論
0/150
提交評論