File类
- 什么是文件?
文件可认为是相关记录或放在一起的数据的集合 - 在Java中,使用java.io.File类对文件进行操作
Flie类常用方法
//创建File对象
File file = new File("c:\\imooc");
File file1 = new File(file, "io\\score.txt");
//判断是文件还是目录
System.out.println("是否是目录:" + file1.isDirectory());
System.out.println("是否是文件:" + file1.isFile());
//创建文件
File file2 = new File("c:\\imooc\\set\\HashSet");
if (!file2.exists()) {
file2.mkdirs();
}
//创建目录
if (!file1.exists()) {
try {
file1.createNewFile();
} catch (IOException var5) {
var5.printStackTrace();
}
}
绝对路径与相对目录
- 绝对路径∶是从盘符开始的路径
- 相对路径∶是从当前路径开始的路径
public static void main(String[] args) {
File f = new File("thread.txt");
try {
f.createNewFile();
//是否是绝对路径
System.out.println(f.isAbsolute());
//是否是相对路径
System.out.println(f.getPath());
//获取绝对路径
System.out.println(f.getAbsolutePath());
//获取文件名
System.out.println(f.getName());
} catch (IOException var3) {
var3.printStackTrace();
}
}
字节流
- 字节输入流InputStream
- 字节输出流OutputStream
FileInputStream
- 从文件系统中的某个文件中获得输入字节
- 用于读取诸如图像数据之类的原始字节流
如果返回值为-1,则表示已经到达文件末尾!!!
FileOutputStream
// 文件拷贝
try {
FileInputStream fis=new FileInputStream("happy.gif");
FileOutputStream fos=new FileOutputStream("happycopy.gif");
int n=0;
byte[] b=new byte[1024];
while((n=fis.read(b))!=-1){
fos.write(b,0,n);
}
fis.close();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
缓冲流
- 缓冲输入流BufferedInputStream
- 缓冲输出流BufferedOutputStream
构造方法
//创建一个 新的缓冲输入流。
public BufferedInputStream(InputStream in) ;
//创建一个新的缓冲输出流。
public BufferedOutputStream(OutputStream out);
字符流
- 字符输入流Reader
- 字符输出流Writer
对象序列化
步骤:创建一个类,继承Serializable接口
创建对象
将对象写入文件
从文件读取对象信息
‘对象输入流ObjectInputStream对象输出流ObjectOutputStream
// 创建一个类,继承Serializable接口
// 创建对象
// 将对象写入文件
// 从文件读取对象信息
// 对象输入流ObjectInputStream
// 对象输出流ObjectOutputStream
public static void main(String[] args) {
// 定义Goods类的对象
Goods goods1 = new Goods("gd001", "电脑", 3000);
try {
FileOutputStream fos = new FileOutputStream("zmz.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
FileInputStream fis = new FileInputStream("zmz.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
// 将Goods对象信息写入文件
oos.writeObject(goods1);
oos.writeBoolean(true);
oos.flush();
// 读对象信息
try {
Goods goods = (Goods) ois.readObject();
System.out.println(goods);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(ois.readBoolean());
fos.close();
oos.close();
fis.close();
ois.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}