File类
基本使用
File file = new File ("hello.txt");
// 获取文件名
System.out.println (file.getName ());
// 获取文件路径
System.out.println (file.getPath ());
// 获取文件的绝对路径,返回 String
System.out.println (file.getAbsolutePath ());
// 获取文件的绝对路径,返回 File
System.out.println (file.getAbsoluteFile ());
// 获取文件的父路径
System.out.println (file.getParent ());
System.out.println (file.getAbsoluteFile ().getParent ());
// 获取文件大小
System.out.println (file.length ());
// 获取文件的最后修改时间
System.out.println (file.lastModified ());
判断功能的方法
/**
* 判断功能的方法
*/
File file = new File ("hello.txt");
file.exists (); // 文件或者目录 是否存在
file.isDirectory (); // 是否为目录
file.isFile (); // 是否是文件
file.canRead (); // 是否可读
file.canWrite ();// 是否可写
file.isHidden (); // 是否隐藏
创建、删除
/**
* 创建、删除
*/
File file = new File ("hello.txt");
file.listFiles ();// 文件目录
if (!file.exists ()) {
// 创建文件,若已存在就返回false
boolean isSuccess = file.createNewFile ();
} else {
// 删除文件或者文件夹
boolean isSuccess = file.delete ();
/**
* 删除注意事项:
* 1、不走回收站
* 2、该目录 不能有文件或者文件夹
*/
}
file.mkdir ();
// 创建多级目录
file.mkdirs ();
printFileName打印文件名
public void printFileName(File file) {
if (file.isFile ()) {
System.out.println (file.getName ());
} else if (file.isDirectory ()) {
File[] files = file.listFiles ();
for (File file1 : files) {
printFileName (file1);
}
}
}
deleteFiles删除文件
public void deleteFiles(File file) {
// 如果是 目录,则递归删除下一级,然后删除掉自己
if (file.isDirectory ()) {
File[] files = file.listFiles ();
for (File f : files) {
deleteFiles (f);
}
}
// 删除掉自己,这里不用else,因为使用 else后就 没有删除目录和子目录,只是删除文件
file.delete ();
}
IO流
深拷贝
重写clone方法,实现深拷贝
涉及到的 所有对象都必须实现Serializable接口
@Override
protected User clone() throws CloneNotSupportedException {
User user = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//ObjectOutputStream是包装流
ObjectOutputStream oos = new ObjectOutputStream(baos);
//写入到 baos流中
oos.writeObject(this);
//将流序列化成对象
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
User o = (User) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return user;
}
FileInputStream与FileOutputStream
FileInputStream fis = null;
FileOutputStream fos = null;
try {
// 1、创建相关的 File对象
File srcFile = new File ("D:\\360安全浏览器下载\\就业情况.jpg");
File descFile = new File ("C:\\Users\\Administrator\\Desktop\\就业情况.jpg");
// 2、创建相关的字节流
fis = new FileInputStream (srcFile);
fos = new FileOutputStream (descFile);
// 3、存储数据的缓冲区
byte[] buffer = new byte[1024]; // 1kb
int len; // 读到的数据长度
// fis.read() 读到buffer
while ((len = fis.read (buffer)) != -1) {
// 将 buffer中的数据写入到fos
fos.write (buffer, 0, len);
fos.flush (); // 将内存中的数据 写入到磁盘文件中
}
} catch (IOException e) {
throw new RuntimeException (e);
} finally {
// 防止内存泄漏!!!
if (fos != null) fos.close ();
if (fis != null) fis.close ();
}
System.out.println ("传输成功!");
OutputStreamWriter与InputStreamReader