Java的IO操作(二) - 带缓冲区的流对象、写入基本数据类型、实现命令行中的copy命令...
在上一節中,我們使用FileInputStream類和FileOutputStream類來實現了一個可以自由拷貝文件的功能。為了提高效率,我們人為地定義一個緩沖區byte[] 數組。其實,我們可以使用BufferedInputStream類和BufferedOutputStream類來重寫這個功能。
5、BufferedInputStream、BufferedOutputStream
看到Buffererd這個詞,我們或許可以猜到,這兩個類應該是帶有緩沖區的流類。正如我們所想的那樣,它們確實有一個buf數據成員,是一個字符數組,默認大小為2048字節。當我們在讀取數據時,BufferedInputStream會盡量將buf填滿;使用read()方法讀取數據時,實際上是先從buf中讀取數據,而不是直接從數據來源(如硬盤)上讀取。只有當buf中的數據不足時,BufferedInputStream才會調用InputStream的read()方法從指定數據源中讀取。
BufferedOutputStream的數據成員buf是一個512字節的字節數組,當我們調用write()方法寫入數據時,實際上是先向buf中寫入,當buf滿后才會將數據寫入至指定設備(如硬盤)。我們也可以手動地調用flush()函數來刷新緩沖區,強制將數據從內存中寫出。
下面用這兩個類實現文件復制功能:
package cls;import java.io.*;public class BufferedStreamDemo {public static void main(String[] args) throws Exception{// 從命令行參數中指定文件File fSource = new File(args[0]);File fDest = new File(args[1]);// 創建帶緩沖的流對象BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fSource));BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fDest));// 提示信息System.out.println("copy " + fSource.length() + "bytes");byte[] buf = new byte[1];while(bis.read(buf) != -1) // read()返回int類型,返回-1表示已到文件結尾bos.write(buf); // 寫入數據// 刷新緩沖區bos.flush();// 關閉流bos.close();bis.close();// 提示信息System.out.println("copy " + fDest.length() + "bytes finished");} }6、DataInputStream和DataOutputStream
DataInputStream和DataOutputStream類提供了對Java基本數據類型寫入的方法,如int,double,boolean。因為Java中基本數據類型的大小是固定的,不會因為不同的機器而改變,因此在寫入的時候就不必擔心不同平臺數據大小不同的問題。
有一個writeUTF()方法值得我們注意。這個方法會將指定的String對象中的字符寫入,但在寫入的數據之前會首先寫入2個字節的長度數據,這個數據指示了帶寫入的字符的大小。這樣的好處是當我們在使用readUTF()讀取數據的時候就不必考慮數據大小的問題了,直接讀取就行,因為在readUTF()內部會控制好讀取數據的長度。
package cls;import java.io.*;class Student {String name;int score;// 構造方法public Student(String name,int score){this.name = name;this.score = score;}// 返回名字public String getName(){return name;}// 返回分數public int getScore(){return score;} }public class DataStreamDemo {public static void main(String[] args) throws Exception{// 創建3個Student對象Student[] sd = new Student[]{new Student("dog",100),new Student("pig",200),new Student("cat",300)};// 創建輸出流對象DataOutputStream dos = new DataOutputStream(new FileOutputStream(args[0])); //向文件中寫入// 使用增強for循環寫入數據for(Student st : sd){dos.writeUTF(st.getName()); // 寫入Stringdos.writeInt(st.getScore());}dos.flush(); // 刷新緩沖區dos.close(); // 關閉流// 從文件中讀入數據DataInputStream dis = new DataInputStream(new FileInputStream(args[0]));for(int i = 0 ; i < 3 ; ++i){System.out.println(dis.readUTF()); // 取入String字符串,不必擔心長度的問題System.out.println(dis.readInt());}dis.close();} }轉載于:https://www.cnblogs.com/whongfei/archive/2013/03/30/5246989.html
總結
以上是生活随笔為你收集整理的Java的IO操作(二) - 带缓冲区的流对象、写入基本数据类型、实现命令行中的copy命令...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用到的oracle sql语句-001
- 下一篇: 站着办公有助减轻体重