FileOutputStream: 屬于寫入位元組流
FileInputStream: 屬于讀取字元流
FileOutputStream
的方法和
FileWriter
的方法基本上大同小異,不過前者是以位元組流的形式寫入,後者以字元流的形式寫入.
FileInputStream
的方法和
FileReader
的方法基本上大同小異,不過前者是以位元組流的形式讀取,後者以字元流的形式寫入.
FileInputStream 有個特殊的方法…能擷取位元組的長度…
available();
FileOutputStream例子:
import java.io.FileOutputStream;
import java.io.IOException;
public class Demo {
public static void main(String[] args) throws IOException{
FileOutputStream fos = new FileOutputStream("bytedemo.txt");
fos.write("abcde".getBytes());
fos.close();
}
}
String類的方法getBytes() 将字元串轉換成字元編碼
運作結果
bytedemo.txt
文本檔案,存入abcde
FileInputStream例子(1):
import java.io.FileInputStream;
import java.io.IOException;
public class Demo {
public static void main(String[] args) throws IOException{
FileInputStream fis = new FileInputStream("bytedemo.txt");
int ch;
ch = fis.read();
System.out.println((char)ch);
fis.close();
}
}
讀取
bytedemo.txt
文本檔案一個位元組流**
運作結果:
FileInputStream例子(2):
如果想要讀取文本檔案全部的内容
使用循環
import java.io.FileInputStream;
import java.io.IOException;
public class Demo {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("bytedemo.txt");
int len = 0;
while ((len = fis.read()) != -1) {
System.out.print((char) len);
}
fis.close();
}
}
運作結果:
FileInputStream例子(3):
使用自己建立緩沖區的位元組流來讀取
使用緩沖區速度會相對變快
import java.io.FileInputStream;
import java.io.IOException;
public class Demo {
private static final int BYTE_SIZE = 1024; //定義位元組流緩沖區大小
public static void main(String[] args) throws IOException{
FileInputStream fis = new FileInputStream("bytedemo.txt");
byte[] buf= new byte[BYTE_SIZE];
int len = 0;
while((len = fis.read(buf)) != -1) {
System.out.print(new String(buf,0,len));
}
fis.close();
}
}
運作結果:
FileInputStream例子(4)
示範avialable()方法
import java.io.FileInputStream;
import java.io.IOException;
public class Demo {
public static void main(String[] args) throws IOException{
FileInputStream fis = new FileInputStream("bytedemo.txt");
int len = 0;
len = fis.available();
System.out.println(len);
}
}
運作結果: 5
檔案裡檢視屬性
可能有人想用available()方法可以擷取大小來定義byte[ ]數組的大小…
import java.io.FileInputStream;
import java.io.IOException;
public class Demo {
public static void main(String[] args) throws IOException{
FileInputStream fis = new FileInputStream("bytedemo.txt");
byte[] buf = new byte[fis.available()];
}
}
但是這種方法要慎用…因為如果這個流并不是文本檔案而是視訊檔案…
檔案大…建立數組的時間就要很久了…或者如果檔案太大…那麼數組還有溢出的風險…會抛出異常.
FileOutputStream 與 FileInputStream 例子:
複制一個Mp3檔案
在D盤目錄放有一個0.mp3的檔案,現在将它複制到F盤中
import java.io.*;
public class Demo {
private static int BYTE_SIZE = 1024;
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("D:\\0.mp3");
FileOutputStream fos = new FileOutputStream("F:\\test.mp3");
int len = 0;
byte[] buf = new byte[BYTE_SIZE];
while((len = fis.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fis.close();
fos.close();
}
}
運作結果: