File类:主要提供了对平台磁盘上文件的操作,一些参考资料上也说这个类是与流无关的。里面的方法很简单,直接查文档就可以了。注意mkdirs方法,可以创建多层目录,还有一个length属性,下面创建byte[]的length使用它就可以。
FileInputStream 类:提供了对文件读取流的操作。由于InputStream,OutputStream是针对字节流的,所以读取文件以前先要定义byte[],然后把文件流读取到byte[]里面。
FileOutputStream类:文件输出流操作。
不管是FileInputStream还是FileOutputStream,流已经打开是不会自动关闭的,所以一定要使用手动关闭流。方法是close();
import java.io.*;
/**
* 文件输入、输出流
*/
public class TestFileInputOutputStream {
public static void main(String[] args) throws Exception {
// 文件读取 FileInputStream, 单位byte
File inputFile = new File("d:\\temp\\read.txt");
FileInputStream fis = new FileInputStream(inputFile);
byte[] byteArr = new byte[(int) inputFile.length()];
fis.read(byteArr);
for (int i = 0; i < byteArr.length; i++) {
System.out.print(byteArr[i]);
}
System.out.println(new String(byteArr));
// 文件写出 FileOutputStream, 单位byte
boolean append = true;
File outFile = new File("d:\\temp\\newread2.txt");
FileOutputStream fos = new FileOutputStream(outFile, append);
fos.write(byteArr);
// 字符串写出, 单位byte
String abc = "abc";
byte[] ab = abc.getBytes();
fos.write(ab);
fis.close();
fos.close();
}
}