File类应用
创建File对象
1.File file=new File("路径");
2.File file=new File("父路径","子路径");
3.File file=new File("父路径");
File file=new File("子路径");
常用方法
file.exists()确定有没有这个文件返回值为Boolean类型
file.mkdir()创建单个目录文件
file.mkdirs()创建多级目录文件
file.createNewFile();
绝对路径与相对路径
绝对路径:C:\\java
相对路径:..\\返回上一级路径(用的更多)
判断:
是否绝对路径:file.isAbsolute();
获取相对路径:file.getPath();
获取绝对路径:file.getAbsolute();
获取文件名:file.getName();
字节流
FileInputStream
FileInputStream fis=new FileInputStream("");
从文件系统中的某个文件中获得输入字节。
用于读取诸如图像数据之类的原始字节流。
循环
while((n=fis.read(字节数组))!=-1){}
方法
public int read() 读取一个字节(返回-1说明读到文件尾)
public void close()关闭此文件输入流并释放与此流有关的所有系统资源
FileOutputStream
FileOutputStream fos=new FileOutputStream(""[,true]);
放入true表示不覆盖以前的内容
用来将数据写到文件中
文件拷贝
FileOutputStream fos=new FileOutputStream("文件名");
FileInputStream fis=new FileInputStream("文件名copy");
int n=0;
byte[] b=new byte[1024];
while((n=fis.read(b))!=-1){fos.write(b,0,n)}
fis.close();
fos.close();
使用这个循环可以保证复试后的文件大小一样
缓冲流
BufferedInputStream
BufferedOutputStream
使用方法
FileOutputStream fos=new FileOutputStream("imook.txt");
BufferedOutputStream bos=new BufferedOutputStream(fos);
FileInputStream fis=new FileInputStream("imook.txt");
BufferedInputStream bis=new BufferedInputStream(fis);
常用方法
bos.write();
bos.flush();
bos.close();
字符流
字节字符转换流
InputStreamReader
是字节流通向字符流的桥梁:它使用指定的 charset 读取字节并将其解码为字符。
它使用的字符集可以由名称指定或显式给定,或者可以接受平台默认的字符集。
OutputStreamWriter
是字符流通向字节流的桥梁:可使用指定的 charset 将要写入流中的字符编码成字节。
它使用的字符集可以由名称指定或显式给定,否则将接受平台默认的字符集。
使用方法
FileOutputStream fos=new FileOutputStream("");
InputStreamReader isr=new InputStreamReader(fos[,"GBK"]);
导入时就转换为GBK
FileInputStream fis=new FileInputStream("");
OutputStreamWriter osw=new OutputStreamWriter(fis[,"GBK"]);
编码一致
其他字符流
FileReader
FileWriter
直接替代以上四行
对象的序列化与反序列化
序列化:把Java对象转换为字节序列的过程
反序列化:把字节序列恢复为 Java对象的过程
步骤
创建一个类,继承Serializable接口
创建对象
将对象写入文件
从文件读取对象信息
对象信息的读取操作
ObjectInputStream
方法:writeObject()
ObjectOutputStream
方法:readObject()(注意读写顺序)
网友评论