輸入和輸出是所有應用中所必需的組成部分,通過IO可以讀取輸入數據以及存儲數據到外部設備上。Java中的輸入和輸出是通過java.io來支持的。下面是本人在學習中的歸納和體會。
1. File類和文件過濾器
顧名思義,File類中是有關文件的操作。這裏必須明確,文件還包括目錄。通過文件或目錄路徑的字符串作爲參數,根據傳入的是目錄路徑還是文件名路徑可以分別初始化不同的File對象。在File對象中封裝了對文件的操作,例如新建文件,刪除文件和重命名等方法。但是它並不能訪問文件本身的內容,這需要輸入輸出流來完成。下面是有關File類的代碼。
- public class FileTest
- {
- public static void main(String[] args) throws IOException
- {
-
- File file = new File(".");
-
- System.out.println(file.getName());
-
- System.out.println(file.getParent());
-
- System.out.println(file.getAbsoluteFile());
-
- System.out.println(file.getAbsoluteFile().getParent());
-
- File tmpFile = File.createTempFile("aaa", ".txt", file);
-
- tmpFile.deleteOnExit();
-
- File newFile = new File(System.currentTimeMillis() + "");
- System.out.println("newFile對象是否存在:" + newFile.exists());
-
- newFile.createNewFile();
-
-
- newFile.mkdir();
-
- String[] fileList = file.list();
- System.out.println("======當前路徑下所有文件和路徑如下=====");
- for (String fileName : fileList)
- {
- System.out.println(fileName);
- }
-
-
- File[] roots = File.listRoots();
- System.out.println("======系統所有根路徑如下=====");
- for (File root : roots)
- {
- System.out.println(root);
- }
- }
- }
|
在上面的代碼中,使用list()方法可以返回目錄下所有文件的路徑和名稱。使用文件過濾器,可以根據自己的需要選擇返回的文件類型。通過一個實現了FilenameFilter接口的類對象作爲list()方法的參數,就可以實現文件過濾的作用。過濾的規則在重寫FilenameFilter中的accept()方法中定義。代碼如下:
- public class FilenameFilterTest
- {
- public static void main(String[] args)
- {
- File file = new File(".");
- String[] nameList = file.list(new MyFilenameFilter());
- for (String name : nameList)
- {
- System.out.println(name);
- }
- }
- }
-
- class MyFilenameFilter implements FilenameFilter
- {
- public boolean accept(File dir, String name)
- {
-
- return name.endsWith(".java")
- || new File(name).isDirectory();
- }
- }
|
2. 輸入輸出流
在Java中,從不同角度定義了輸入輸出流的分類。以內存作爲流的方向基點,可將其分爲輸入流和輸出流,流向內存的成爲輸入流,流出內存的成爲輸出流。從數據操作的最小單元來分類,可將其分爲字節流和字符流。根據抽象程度分類,可將其分爲節點流和處理流,處理流是連接到實際物理節點的節點流的封裝,這樣既可以不必去關注節點的來源(文件或者數組),用統一的方法去操作,又可以使用更加方面的方法來實現操作。
在學習中,本人對於輸入輸出流的總結歸納:
A. 字節流和字符流其實並沒有本質的區別,無非是它們二者的操作單元不同。字節流的基類爲InputStream和OutputStream,字符流的基類爲Reader和Writer。它們所提供的讀寫方法一樣,區別在於參數,需要對應流類型。
B. 輸入流中的read系列方法是從輸入流中讀取數據的操作。空參數將返回所讀取的字節(字符)。read方法中可以傳入數組參數,數組的類型必須和流的數據類型相匹配,相當於一個竹筒,一次可讀取最多等於數組容量的數據,並將所讀數據裝進數組中。
C. 輸出流中的write系列方法是向輸出流中寫入數據的操作。方法中的參數可以是整型或字符型變量,也可以傳入數組參數,數組的類型必須和流的數據類型相匹配,相當於一個竹筒,一次可寫入最多等於數組容量的數據。特別地,字符型輸出流的write方法可以傳入字符串。
D. InputStream和OutputStream,Reader和Writer這四個類作爲Java中輸入輸出流的抽象基類,並不能直接被初始化使用。Java中提供了一些繼承了它們的類,用於實現具體的某種流操作。如:
a.File前綴系列的類(如FileInputStream),用於對文件類進行流操作,使用文件名作爲構造函數的參數;示例代碼如下:
輸出類:
- public class FileOutputStreamTest
- {
- public static void main(String[] args) throws IOException
- {
- FileInputStream fis = null;
- FileOutputStream fos = null;
- try
- {
-
- fis = new FileInputStream("FileOutputStreamTest.java");
-
- fos = new FileOutputStream("newFile.txt");
- byte[] bbuf = new byte[32];
- int hasRead = 0;
-
- while ((hasRead = fis.read(bbuf)) > 0 )
- {
-
- fos.write(bbuf , 0 , hasRead);
- }
- }
- catch (IOException ioe)
- {
- ioe.printStackTrace();
- }
- finally
- {
-
- if (fis != null)
- {
- fis.close();
- }
-
- if (fos != null)
- {
- fos.close();
- }
- }
- }
- }
|
輸入類:
- public class FileInputStreamTest
- {
- public static void main(String[] args) throws IOException
- {
-
- FileInputStream fis = new FileInputStream("FileInputStreamTest.java");
-
- byte[] bbuf = new byte[1024];
-
- int hasRead = 0;
-
- while ((hasRead = fis.read(bbuf)) > 0 )
- {
-
- System.out.print(new String(bbuf , 0 , hasRead ));
- }
- fis.close();
- }
- }
|
b. 數組前綴系列類(如ByteArrayInputSteam),用於對數組進行流操作,使用數組對象作爲構造函數的參數;
c. 轉換流InputStreamReader將字節輸入流轉換爲字符輸入流;InputStreamReader將字節輸出流轉換爲字符輸出流,代碼如下:
- public class KeyinTest
- {
- public static void main(String[] args)
- {
- BufferedReader br = null;
- try
- {
-
- InputStreamReader reader = new InputStreamReader(System.in);
-
- br = new BufferedReader(reader);
- String buffer = null;
-
- while ((buffer = br.readLine()) != null)
- {
-
- if (buffer.equals("exit"))
- {
- System.exit(1);
- }
-
- System.out.println("輸入內容爲:" + buffer);
- }
- }
- catch (IOException ioe)
- {
- ioe.printStackTrace();
- }
-
- finally
- {
- try
- {
- br.close();
- }
- catch (IOException ioe)
- {
- ioe.printStackTrace();
- }
- }
- }
- }
|
d. 字符流的子類有String前綴(StringReader和StringWriter)系列類可以對字符串進行操作,代碼如下:
- public class StringNodeTest
- {
- public static void main(String[] args)
- {
- String src = "從明天起,做一個幸福的人\n"
- + "餵馬,劈柴,周遊世界\n"
- + "從明天起,關心糧食和蔬菜\n"
- + "我有一所房子,面朝大海,春暖花開\n"
- + "從明天起,和每一個親人通信\n"
- + "告訴他們我的幸福\n";
- StringReader sr = new StringReader(src);
- char[] buffer = new char[32];
- int hasRead = 0;
- try
- {
-
- while((hasRead = sr.read(buffer)) > 0)
- {
- System.out.print(new String(buffer ,0 , hasRead));
- }
- }
- catch (IOException ioe)
- {
- ioe.printStackTrace();
- }
- finally
- {
- sr.close();
- }
-
-
- StringWriter sw = new StringWriter(20);
-
- sw.write("我遠離了大海,\n");
- sw.write("看不到春暖花開,\n");
- sw.write("我只有一隻小龜,\n");
- sw.write("一樣可以聞到馥郁花香\n");
- System.out.println("------下面是sw的字符串節點裏的內容------:");
-
- System.out.println(sw.toString());
- }
- }
|
d.推回輸入流PushbackInputStream和PushbackReader帶有一個推回緩衝區,使用unread(數組)方法可以將一個字節/字符數組推回到推回緩衝區中。推回輸入流也有read方法,使用read方法讀取輸入流時,首先從輸入緩衝區中讀取,讀完之後才從輸入流中讀。代碼如下:
- public class PushbackTest
- {
- public static void main(String[] args)
- {
- PushbackReader pr = null;
- try
- {
-
- pr = new PushbackReader(new FileReader("PushbackTest.java") , 64);
- char[] buf = new char[32];
-
- String lastContent = "";
- int hasRead = 0;
-
- while ((hasRead = pr.read(buf)) > 0)
- {
-
- String content = new String(buf , 0 , hasRead);
- int targetIndex = 0;
-
-
- if ((targetIndex = (lastContent + content).indexOf("new PushbackReader")) > 0)
- {
-
- pr.unread((lastContent + content).toCharArray());
-
- pr.read(buf , 0 , targetIndex);
-
- System.out.print(new String(buf , 0 ,targetIndex));
- System.exit(0);
- }
- else
- {
-
- System.out.print(lastContent);
-
- lastContent = content;
- }
- }
- }
- catch (IOException ioe)
- {
- ioe.printStackTrace();
- }
- finally
- {
- try
- {
- if (pr != null)
- pr.close();
- }
- catch (IOException ioe)
- {
- ioe.printStackTrace();
- }
- }
- }
- }
|
E. 在Java虛擬機中可以通過exec方法執行其他的應用程序,並返回Proess對象。利用該對象的getErrorStream、getInputStream和getOutputStream方法可以分別獲得子進程的錯誤流,輸出流和輸入流(方向是以程序角度爲基點)。
F. RandomAccessFile類提供對文件的隨機訪問,程序可以直接跳轉到文件的任何地方來讀取數據。它內部提供了與字節流同法相同的讀寫方法,另外又加入了自由定位文件記錄指針的方法seek。在讀寫操作時以字節爲單位。在構造函數中還需加入一個mode參數由於制定讀寫權限。
G. 需要注意Scanner對象的使用。Scanner對象用於捕獲輸入,並將輸入內容轉換爲字符串。
-
- Scanner sc = new Scanner(System.in);
- PrintStream ps = new PrintStream(
- new FileOutputStream("out.txt"));
-
- sc.useDelimiter("\n");
-
- while(sc.hasNext())
- {
-
- ps.println("鍵盤輸入的內容是:" + sc.next());
- }
- ps.close();
|
對於初學者來說一個容易忽略的地方是,需要區別節點流和處理流構造方法中參數的意義。節點流中,構造方法參數是要讀取或者輸出地物理節點,是“目的地”或者“始發地”,而處理流的構造函數參數是所要包裝的處理流對象,包裝之後的操作實際上是間接操作節點流,並未對被包裝的節點流本身屬性做修改。採用處理流包裝後,可以不用管節點流的數據類型,而根據處理流的性質傳遞在節點流中不能傳遞的內容,例如Obj;同時還可以增加一些便於操作的方法,比如緩衝區。