文件基础知识

130 阅读2分钟

什么是文件:文件就是存储数据的地方

文件流:文件在程序中是以流的形式来操作的

流:数据在数据源和程序之间经历的路径

输入流:数据从数据源到程序的路径(磁盘 到 内存)

输出流:数据从程序到数据源的路径(内存 到 磁盘)

常用的文件操作

创建文件对象相关构造器和方法

new File(String pathname) 根据路径构建一个File对象

//new File(String pathname) 根据路径构建一个File对象
//直接写出完整路径
String  filePath = "D:\new1.txt";

File file = new File(filePath);

try {
    file.createNewFile();
    System.out.println("文件创建成功");
} catch (IOException e) {
    e.printStackTrace();
}

new File(File parent , String child) 根据父目录文件+子路径构建

//new File(File parent , String child) 根据父目录文件+子路径构建
 //在父目录下创建文件
 // new File() 只是相当于在内存中创建了对象
 // 只有执行了createNewFile方法才会真正的在磁盘中创建该文件
 public void create2(){
     File file = new File("D:\");

     String filename = "news2.txt";

     File file1 = new File(file, filename);

     try {
         file1.createNewFile();
         System.out.println("方式二创建文件夹成功");
     } catch (IOException e) {
         e.printStackTrace();
     }
 }

new File(String parent , String child)根据父目录+子路径构建

@Test
public void creat3(){
    String parentPath = "d:\";
    String filePath = "news3.txt";
    File file = new File(parentPath, filePath);
    try {
        file.createNewFile();
        System.out.println("方法三创建成功");
    } catch (IOException e) {
        e.printStackTrace();
    }

}

createNewFile 创建新文件

获取文件相关信息
public void info(){
    //先创建文件对象
    File file = new File("d:\new1.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());


}
目录操作和文件删除

mkdir创建一级目录,mkdirs创建多级目录,delete删除空目录或文件


//判断目录是否存在
//体会一下 在java中目录也被当做文件
@Test
public void m2() {
    String filePath = "D:\demo01";
    File file = new File(filePath);
    if (file.exists()) {
        if (file.delete()) {
            System.out.println("删除文件成功");
        } else {
            System.out.println("删除文件失败");
        }
    } else {
        System.out.println("文件不存在");
    }

}
//判断目录是否存在,存在就提示存在,不存在就创建
@Test
public void m3() {
    String filePath = "D:\demo01";
    File file = new File(filePath);
    if (file.exists()) {
        System.out.println("目录已存在");
    } else {
            file.mkdirs();
            System.out.println("创建目录成功");
    }

}