看,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();
}
}
}
}