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("创建失败");
            }
        }
    }
复制代码

 

posted @   长空扯淡  阅读(80)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示