java中inputstream的使用,javainputstream

來源:互聯網
上載者:User

java中inputstream的使用,javainputstream

java中的inputstream是一個面向位元組的流抽象類別,其根據具體應用派生出各種具體的類。

比如FileInputStream就是繼承於InputStream,專門用來讀取檔案流的對象,其具體繼承結構



我們發現,是從抽象類別InputStream繼承而來的。


我們繼續看例子,實現從txt檔案中,讀取字元。其中test.txt已經提前建立好,放到工程目錄下了。

package com.itbuluoge.test;import java.io.FileInputStream;public class ByteInputFile {public static String read() throws Exception{FileInputStream fit=new FileInputStream("test.txt");int c;String sb="";while((c=fit.read())!=-1){sb+=(char)c;}return sb;}/** * @param args * @throws Exception  */public static void main(String[] args) throws Exception {// TODO Auto-generated method stubSystem.out.println(read());}}


輸出結果




這裡要注意一點,InputStream是面向位元組的流,因此每次操作都是針對於一個位元組,因此就無法對中文進行處理,讀出寫入都會出現亂碼。繼承而來的FileInputStream是一樣的。因此我們這裡測試,只是用了英文字元


JAVA中,同時使用FileInputStream類與FileOutputStream類

InputStream is = new FileInputStream(C:\Java\a.txt);
File destFile = new File("路徑",檔案名稱);
OutputStream os = new FileOutputStream(destFile);
byte[] buffer = new byte[400];
int length = 0 ;
while((length = is.read(buffer))>0){
os.write(buffer, 0, length);
}
is.close();
os.close();
 
JAVA中DateInputStream的使用

是要解釋這段代碼嗎?

java中io這部分代碼使用了裝飾器(Decorator)設計模式。
DataInputStream、BufferedInputStream和FileInputStream都是InputStream的子類,分的更細一點,DataInputStream、BufferedInputStream是FilterInputStream的子類

每一個FilterInputStream都有一個構造方法
new FilterInputStream(InputStream in),能夠接受一個InputStream對象,在其上裝飾一層新的功能,比如BufferedInputStream就加了緩衝區,DataInputStream就加上讀各種基本類型資料,如byte、int、String的功能

比如第二段代碼
DataInputStream fis = new DataInputStream(new BufferedInputStream( new FileInputStream(filePath)));
就在一個檔案流上裝飾了緩衝區、以及對各基本類型資料的讀操作
而第一段代碼的
dis.readByte()就在輸入資料流中讀取一個byte
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.