IO流第31天(文件流,创建文件的3种方式,获取文件的相关信息)

IO流

文件

文件是保存数据的地方,例如Word文档,Excel文件等,既可以保存图片,也可以保存视频,声音等

文件流

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

创建文件

  1. new File(String pathname)//根据路径构造一个file对象
  2. new File(File parent,String child)//根据父目录文件+子路径构建
  3. new File(String parent,String child)//根据父目录+子路径构建
    第一个方法是直接指定路径创建文件,第二种是根据已知文件名创建新文件在那已知的目录上,第三种是通过路径,通过已知旧文件路径创建
    creatNewFile()方法创建新文件
//方式一 new File(String pathname)根据路径构造一个file对象
    @Test
    public void create01(){
        String filePath="d:\\news1.txt";
        File file = new File(filePath);//此处的file对象在java程序中只是一个对象
        try {
            file.createNewFile();//执行了createNewFile()方法才会真正在磁盘创建该文件
            System.out.println("文件创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //方式二new File(File parent,String child)//根据父目录文件+子路径构建
    @Test
    public void create02(){
        //e:\\new2.txt
        File parentFile = new File("d:\\");
        //String parentFile="d:\\";
        String fileName="news2.txt";
        File file = new File(parentFile, fileName);

        try {
            file.createNewFile();
            System.out.println("文件news2创建成");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //方式三:new File(String parent,String child)//根据父目录+子路径构建
    @Test
    public void create03()
    {
        String parentPath="d:\\";
        String filePath="news3.txt";
        File file = new File(parentPath, filePath);

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

获取文件相关信息

方法名 方法作用
getName() 获取文件名
getAbsolutePath() 获取文件路径
getParent() 获取父级目录
length() 获取文件长度(按字节统计,一个英文字母一个字节,一个汉字3个字节)
exists() 判断该文件是否存在(True/False)
isFile() 判断是否为文件(True/False)
isDirectory() 判断是否为目录(True/False)
//先创建文件对象
        File file = new File("d:\\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());
        System.out.println("是否是文件=="+file.isFile());
        System.out.println("是不是目录=="+file.isDirectory());

image

posted @   不再犹豫27  阅读(72)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示