FileInputStream:
文件读取流,从文件中读取数据。
构造方法:
InputStream f = new FileInputStream("path");
或
File f = new File("path");//创建文件对象
InputStream out = new FileInputStream(f);
常用方法:
- void close() throws IOException{}关闭输入流并释放与有关所有系统资源
- void finalize()throws IOException {}清除与该文件的连接。不再引用时调用 close 方法
- int read(int r)throws IOException{}返回下一字节数据,结尾则返回-1
- int read(byte[] r) throws IOException{}读取r.length长度的字节,结尾则返回-1
- int available() throws IOException{}返回下一次对此不受阻塞地字节数。
FileOutputStream:
文件输出流,向文件写入数据。
常用方法:
- void write(int w)throws IOException{} //把指定的字节写到输出流中
- void write(byte[] w) //把指定数组中w.length长度的字节写到OutputStream中
File:
文件类
常用方法:
- boolean mkdir(); //创建一个文件夹,成功则返回true,失败则返回false。
- boolean mkdirs(); //创建一个文件夹和它的所有父文件夹。
- boolean renameTo(File dest) //重新命名此抽象路径名表示的文件。
- boolean createNewFile() //当不存在此抽象路径名指定名称的文件时,创建一个空文件。
- boolean delete() //删除指定路径的文件或目录。
- boolean exists() //测试文件是否存在
- String getParent ()//返回此抽象路径名父目录的路径名字符串;不存在,返回null。
实例应用
//文件流读写
public class fileStreamTest{
public static void main(String args[]){
try{
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt");
for(int x=0; x < bWrite.length ; x++){
os.write( bWrite[x] ); // writes the bytes
}
os.close();//关闭输入流
InputStream is = new FileInputStream("test.txt");
int size = is.available();
for(int i=0; i< size; i++){
System.out.print((char)is.read() + " ");
}
is.close();//关闭读取流
}catch(IOException e){
System.out.print("Exception");
}
}
}
//创建指定文件
private static void createFile(String _path, String _filename) {
String filepath = _path + "\\" + _filename;//设置指定路径
File file = new File(filepath);
//当目录不存在时
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();//创建文件夹路径
}
//当文件不存在时
if (!file.exists()) {
try {
file.createNewFile();//创建指定文件
} catch (IOException e) {
System.err.println("创建 " + file + " 失败!");
}
}
}