Java Input/Output

 

1. 簡單的使用方式html

java.util.Scanner (讀)java

Scanner sc = new Scanner(System.in);
String str1 = sc.nextLine();

java.io.PrintWriter  (寫)git

Writer writer = new PrintWriter("abc.txt");

   

Java的IO操做中有面向字節(Byte)和麪向字符(Character)兩種方式  (注意命名後綴)github

 

2. 二進制IOapi

可序列化接口Serializable數組

能夠寫入輸出流中的對象成爲可序列化的,可序列化對象的類必須實現Serizlizable接口。性能優化

Serialzable接口是一種標記性接口,由於它沒有方法,因此不須要在類中爲實現Serializable接口增長額外的代碼。實現這個接口能夠啓動Java的序列化機制,自動你完成存儲對象和數組的過程。bash

關鍵字transient告訴Java虛擬機將對象寫入對象流時忽略這些數據域。多線程

 

序列化數組oracle

只有數組中的元素都是可序列化的,這個數組纔是可序列化的。一個完整的數組能夠用writeObject方法存入文件,隨後用readObject方法恢復。

示例:

 1 package com.artificerpi.demo;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 import java.io.ObjectInputStream;
 7 import java.io.ObjectOutputStream;
 8 import java.io.Serializable;
 9 
10 public class Hello {
11     public static void main(String[] args) throws ClassNotFoundException, IOException {
12         int[] numbers = { 1, 2, 3, 4, 5 };
13         String[] strings = { "John", "Jim", "Jake" };
14         Programmer programmer = new Programmer("artificerpi", 17);
15         ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("array.dat", false)); // no
16                                                                                                         // append
17 
18         output.writeObject(numbers);
19         output.writeObject(strings);
20         output.writeObject(programmer);
21 
22         output.close();
23 
24         ObjectInputStream input = new ObjectInputStream(new FileInputStream("array.dat"));
25 
26         int[] nums = (int[]) input.readObject();
27         String[] strs = (String[]) input.readObject();
28         Programmer programmer2 = (Programmer) input.readObject();
29 
30         for (int a : nums) {
31             System.out.print(a);
32         }
33         System.out.println();
34 
35         for (String s : strs) {
36             System.out.print(s);
37         }
38 
39         System.out.println(programmer2.name + programmer2.age);
40 
41     }
42 }
43 
44 class Programmer implements Serializable {
45     String name;
46     transient int age;
47 
48     public Programmer(String name, int age) {
49         this.name = name;
50         this.age = age;
51     }
52 
53 }
View Code

 

 

隨機訪問文件RandomAccessFile

  RandomAccessFile類直接繼承於Object類,它並不屬於Streams結構的一部分。    

     public class RandomAccessFile implements DataOutput, DataInput, Closeable {

  RandomAccessFile類實現了DataInput和DataOutput接口,容許在文件內的隨機位置上進行讀寫。

  當建立一個RandomAccessFile數據流時,能夠指定兩種模式(「r",只讀或」rw",既容許讀也容許寫)。

RandomAccessFile raf = new RandomAccessFile("test.dat", "rw");

隨機訪問文件是由字節序列組成的。一個稱爲文件指針(file pointer)的特殊標記定位這些字節中的某個位置。文件的讀寫操做就是在文件指針所指的位置上進行的。打開文件時,文件指針置於文件的起始位置。在文件中進行讀寫數據後,文件指針就會向前移到下一個數據項。

 

 1 package com.artificerpi.demo;
 2 
 3 import java.io.IOException;
 4 import java.io.RandomAccessFile;
 5 
 6 public class Hello {
 7     public static void main(String[] args) throws IOException {
 8         RandomAccessFile raf = new RandomAccessFile("input.dat", "rw");
 9 
10         // Clear the file to destroy the old contents, if any
11         raf.setLength(0);
12 
13         // Write new integers to the file
14         for (int i = 0; i < 200; i++) {
15             raf.writeInt(i); // an integer accounts for 4 bytes
16         }
17 
18         System.out.println("Current file length is:" + raf.length());
19 
20         raf.seek(0);
21         System.out.println("The first number is " + raf.readInt());
22 
23         // Retrieve the tenth number
24         raf.seek(9 * 4);
25         System.out.println("The tenth number is: " + raf.readInt());
26 
27         raf.writeInt(555); // modify the eleventh number
28 
29         raf.seek(raf.length());
30         raf.writeInt(998);
31 
32         System.out.println("The new length is " + raf.length());
33 
34         raf.seek(10 * 4);
35         System.out.println("The eleventh number is " + raf.readInt());
36 
37         raf.close();
38     }
39 }
Current file length is:800
The first number is 0
The tenth number is: 9
The new length is 804
The eleventh number is 555

 

Closeable

Closeable is a source or destination of data that can be closed. The close method is invoked to release resources that the object is holding (such as open files).

void close()    Closes this stream and releases any system resources associated with it.

 

AutoColseable 繼承了Closeable

Closes this resource, relinquishing any underlying resources. This method is invoked automatically on objects managed by the try-with-resources statement.

 

Flushable

 A Flushable is a destination of data that can be flushed. The flush method is invoked to write any buffered output to the underlying stream.

void flush() Flushes this stream by writing any buffered output to the underlying stream.

 

 

Writer.close() 實現一個writer通常在close流以前要flush(雖然不少實現類的flush沒有什麼操做). PrintWriter構造函數就有一個參數設定是否自動flush

通常而言,若是使用了Buffer,應謹慎處理流的關閉,弄清楚flush的必要性,不然不要省略。

/**
* Closes the stream, flushing it first. Once the stream has been closed,
* further write() or flush() invocations will cause an IOException to be
* thrown. Closing a previously closed stream has no effect.
*
* @throws IOException
* If an I/O error occurs
*/
public abstract void close() throws IOException;

java.io.BufferedWriter close()方法就調用了flushBuffer(), 注意不是flush()

 @SuppressWarnings("try")
    public void close() throws IOException {
        synchronized (lock) {
            if (out == null) {
                return;
            }
            try (Writer w = out) {
                flushBuffer();
            } finally {
                out = null;
                cb = null;
            }
        }
    }

  

 

相似地,在實現一個壓縮的Filter的時候,若是用到 ServletResponseWrapper 類, 在close流以前(finish數據傳輸以前)應該flush,不然reponse可能會顯示爲空(例如encoding 爲chunked)。注意其flushBuffer的做用:

Forces any content in the buffer to be written to the client. A call to this method automatically commits the response, meaning the status code and headers will be written.

ServletResponse.flushBuffer() 

    public void flushBuffer() throws IOException;

 

Java 輸入輸出流性能優化

http://www.oracle.com/technetwork/articles/javase/perftuning-137844.html

 

更多代碼

  JGet 一個簡單的Java實現的多線程下載工具。

 

參考:

http://www.cnblogs.com/lanxuezaipiao/p/3371224.html

相關文章
相關標籤/搜索