看,API說的多簡單啊:
FileInputStream
用於讀取諸如圖像數據之類的原始字節流。要讀取字符流,請考慮使用
FileReader
。
FileOutputStream
用於寫入諸如圖像數據之類的原始字節的流。要寫入字符流,請考慮使用
FileWriter
。
FileInputStream與FileOutputStream都是字節流,所以它們都是用來讀byte與寫byte的。
上例子:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileStreamTest {
public static void main(String[] args) {
// writeTest();
// readTest_1();
// readTest_2();
// readTest_3();
// copyFile();
}
// 用字節流文件的讀寫。
private static void copyFile() {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("F:\\library.rar");
fos = new FileOutputStream("F:\\library_copy.rar");
byte[] buf = new byte[1024];
int len = 0;
while ((len = fis.read(buf)) != -1) {
fos.write(buf, 0, len);
}
System.out.println("複製完成");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void readTest_3() {
FileInputStream fis = null;
try {
fis = new FileInputStream("D:\\log.txt");
// available()方法是用於創建一個大小剛剛適合的緩衝區,不過如果資源文件過大的話,很容易造成內在溢出的問題。
byte[] buf = new byte[fis.available()];
fis.read(buf);
System.out.println(new String(buf));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void readTest_2() {
FileInputStream fis = null;
try {
fis = new FileInputStream("D:\\log.txt");
byte[] buf = new byte[1024];
int len = 0;
while ((len = fis.read(buf)) != -1) {
System.out.println(new String(buf, 0, len));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void readTest_1() {
FileInputStream fis = null;
try {
fis = new FileInputStream("D:\\log.txt");
int b = 0;
while ((b = fis.read()) != -1) {
System.out.println((char) b);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void writeTest() {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("D:\\log.txt");
// 字節流操作的是字節數組。字符流操作的是字符數組。
fos.write("abcdefg".getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}