一、文件基础知识
1、什么是文件
文件,对我们并不陌生,文件是保存数据的地方,比如大家经常使用的word文档,txt文档,excel文件...都是文件.它既可以保存一张图片也可以保持视频,声音...
2、文件流
文件在程序中是以流的形式来操作的
流:数据在数据源(文件)和程序(内存)之间经历的路径
输入流(读):数据从数据源(文件)到程序(内存)的路径
输出流(写):数据从程序(内存)到数据源(文件)的路径
二、创建文件
1、创建文件的三种方式
/** * 创建文件对象的三种方式 * new File (String pathName) // 根据路径创建一个File对象 * new File (File parent, String child) // 根据父目录文件 + 子路径创建 * new File (String parent, String child) // 根据父目录 + 子路径创建 */ @Test public void test01(){ // 1、new File (String pathName) File file = new File("e:\\mine\\注意事项.txt"); if (file.exists()){ System.out.println("文件已存在!"); } else { System.out.println("文件不存在,正在创建!"); try { file.createNewFile(); System.out.println(file.getName() + "创建成功!"); } catch (IOException e) { System.out.println(file.getName() + "创建失败!"); e.printStackTrace(); } } } @Test public void test02(){ // 2、new File (File parent, String child) File parentFile = new File("e:\\mine\\"); String fileName = "推选.xls"; File file = new File(parentFile,fileName); if (file.exists()){ System.out.println("文件已存在!"); } else { System.out.println("文件不存在,正在创建!"); try { file.createNewFile(); System.out.println(file.getName() + "创建成功!"); } catch (IOException e) { System.out.println(file.getName() + "创建失败!"); e.printStackTrace(); } } } @Test public void test03(){ // 3、new File (String parent, String child) String parentName = "e:\\mine\\"; String fileName = "民政大脑.doc"; File file = new File(parentName,fileName); if (file.exists()){ System.out.println("文件已存在!"); } else { System.out.println("文件不存在,正在创建!"); try { file.createNewFile(); System.out.println(file.getName() + "创建成功!"); } catch (IOException e) { System.out.println(file.getName() + "创建失败!"); e.printStackTrace(); } } }
2、获取文件信息
/** * 获取文件信息 */ @Test public void test04(){ // 该文件需存在 File file = new File("e:\\mine\\注意事项.txt"); System.out.println("文件名字=" + file.getName()); System.out.println("文件绝对路径=" + file.getAbsolutePath()); System.out.println("文件父级目录=" + file.getParent()); System.out.println("文件大小=" + file.length()); System.out.println("文件是否存在=" + file.exists()); System.out.println("是不是一个文件=" + file.isFile()); System.out.println("是不是一个目录=" + file.isDirectory()); }
3、目录操作 (创建一级目录用mkdir、多级目录用mkdirs)
/** * 目录操作 */ @Test public void test05(){ // 该文件需存在 String filePath = "e:\\mine\\注意事项.txt"; File file = new File(filePath); if (file.exists()){ if (file.delete()){ System.out.println("文件已删除!"); } else { System.out.println("文件删除失败!"); } } else { System.out.println("文件不存在!"); } } /** * 删除目录 delete只能删除空目录 */ @Test public void test06(){ // 该文件需存在 String filePath = "e:\\new\\two\\aim"; File file = new File(filePath); if (file.exists()){ System.out.println(filePath + "存在!"); } else { if (file.mkdirs()){ System.out.println(filePath + "创建成功!"); } else { System.out.println(filePath + "创建失败!"); } } }