IO流(1)创建文件
文件流:文件在程序中是以流的形式来操作的。
输入流:数据从数据源(文件)到程序(内存)的路径
输出流:数据从程序(内存)到数据源(文件)的路径
创建文件
- new File(String pathname)//根据路径构造一个File对象
- new File(File parent,String child)//根据父目录文件+子目录构建
- new File(String parent,String child)//根据父目录+子路径构建
createNewFile 创建新文件
@Test //方式1:new File(String pathname) public void create01(){ String filePath="e:\\news1.txt"; File file = new File(filePath); //File file = new File("e:\\news1.txt"); try { file.createNewFile(); System.out.println("创建成功"); } catch (IOException e) { e.printStackTrace(); } } @Test //方式2:new File(File parent,String child)//根据父目录文件+子路径构建 //e:\\news2.txt public void create02(){ File parentFile = new File("e:\\");//父 String fileName = "news2.txt";//子 File file = new File(parentFile, fileName); try { file.createNewFile(); System.out.println("创建成功"); } catch (IOException e) { e.printStackTrace(); } } @Test //方式3:new File(String parent,String child)//根据父目录+子路径构建 public void create03(){ File parentPath = new File("e:\\"); String fileName = "names3.txt"; File file = new File(parentPath, fileName); try { file.createNewFile(); System.out.println("创建成功"); } catch (IOException e) { e.printStackTrace(); } }
获取文件信息
package IO; import java.io.File; public class Test { public static void main(String[] args) { } //获取文件信息 @org.junit.Test public void information(){ File file = new File("e:\\news1.txt"); //调用相印的方法,得到对应的信息 System.out.println("文件名字:"+file.getName()); System.out.println("文件绝对路径:"+file.getAbsolutePath()); System.out.println("文件父级目录:"+file.getParent()); System.out.println("文件大小(字节):"+file.length());//一个字母占一个字节,中文占3个 System.out.println("文件是否存在:"+file.exists());//T System.out.println("是不是一个文件:"+file.isFile());//T System.out.println("是不是一个目录:"+file.isDirectory());//F } }
创建一级目录使用mkdir();,创建多级目录使用mkdirs();
//判断f:\\demo\\a\\b\\c目录是否存在,不存在就创建 @Test public void m3(){ String directoryPath = "f:\\demo\\a\\b\\c"; File file = new File(directoryPath); if (file.exists()){ System.out.println(directoryPath+"存在"); }else{ if(file.mkdirs()){//创建一级目录使用mkdir();,创建多级目录使用mkdirs(); System.out.println(directoryPath+"创建成功"); }else{ System.out.println("创建失败"); } } }
浙公网安备 33010602011771号