之前的接觸過IO的字符流內容,在字符流中,通過緩衝流的方法可以便捷的將要複製的文本文件複製到新的文件中去,可是如果我們想複製一個.png的圖片或者一些不是單純文本文件的內容的時候能在字符流中做到嗎?經過測試,字符流是無法將圖片等非字符形式的文件複製的,那麼就要用到另一個流-à字節流,
字節流:
在數據傳輸過程中,一切數據(文本、圖像、聲音等)最終存儲的均爲一個個字節,即二進制數字。所以數據傳輸過程中使用二進制數據可以完成任意數據的傳遞。
我們向一個文件中存儲一定的數據(一些數字),如果使用文本方式打開,則會以文本的方式解釋數據。如果以視頻的方式打開,則會以視頻的方式解釋數據。音頻、可行執行文件等是如此。所以,在文件傳輸過程中,傳輸的始終爲二進制數據。
字節流裏主要包括InputStream和OutputStream
InputStream此抽象類,是表示字節輸入流的所有類的超類。,定義了字節輸入流的基本共性功能方法。InputStream有很多子類,其中子類FileInputStream可用來讀取文件內容。FileInputStream 從文件系統中的某個文件中獲得輸入字節。
OutputStream此抽象類,是表示輸出字節流的所有類的超類。操作的數據都是字節,定義了輸出字節流的基本共性功能方法。OutputStream有很多子類,其中子類FileOutputStream可用來寫入數據到文件。FileOutputStream類,即文件輸出流,是用於將數據寫入File
的輸出流。
舉例說明:
java.io.InputStream 字節輸入流的抽象基類
常用方法
intread() 一次讀一個字節
intread(bytes[] byte) 一次讀一個數組
FileInputStream extends InputStream
構造方法 綁定數據源
publicFileInputStream(File file)
publicFileInputStream(String path)
參數
File對象
String路徑
public class Demo01_InputStream {
publicstatic void main(String[] args) throws IOException {
//創建字節輸入流對象 綁定數據源
InputStream is = newFileInputStream("d:\\work\\abc\\1.txt");
intlen = 0;//每次讀取到的數據
while((len= is.read())!=-1){
System.out.println(len);
}
// intlen = is.read();
// System.out.println(len);
// len= is.read();
// System.out.println(len);
// len= is.read();
// System.out.println(len);
// len= is.read();
// System.out.println(len);
//
is.close();
}
}
java.io.OutputStream 所有字節輸出流的超類
常用方法
write(intb )
write(byte[]bytes) 寫一個字節數組
write(byte[]bytes,int start ,int length) 寫字節數組的一部分
FileOutputStream extends OutputStream
構造方法 綁定數據目的
publicFileOutputStream(File file)
publicFileOutputStream(String path)
參數
File對象
String路徑
如果沒有文件則創建文件 如果有文件則覆蓋文件
public class Demo01_OutputStream {
publicstatic void main(String[] args) throws IOException {
//創建字節輸出流對象
OutputStreamos = new FileOutputStream("d:\\work\\abc\\1.txt")
os.write(100);
os.write(49);
os.write(48);
os.write(48);
os.write('1');
byte[]bytes = {97,98,99,100};
os.write(bytes);
os.write(bytes,2, 2);
最後介紹一下如何將複製過來的文件換行打印和,在新文件以有的文件內續寫文件.
續寫
FileOutputStream的構造方法
FileOutputStream(Filefile, boolean append)
FileOutputStream(Stringname, boolean append)
參數
booleanappend:值爲true則續寫文件 值爲false則覆蓋文件
換行:\r\n
public class Demo_OutputStream {
publicstatic void main(String[] args) throws IOException {
OutputStreamos = new FileOutputStream("d:\\work\\abc\\1.txt",true);
os.write("nihao\r\n".getBytes());
os.write("wohao\r\n".getBytes());
os.write("大家好".getBytes());
os.close();
}
}