Java File.createNewFile 创建文件的四种方式小笔记

1.File(String pathname):根据一个路径得到File对象

2.File(String parent,String child):根据一个目录和一个子文件/目录得到File对象

3.File(File parent,String child):根据一个父File对象和一个子文件/目录得到File对象

4.File(URI uri):根据路径的uri创建File对象

代码示例如下:

package com.joshua317;

import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class Main {
    public static void main(String[] args) {
    }

    @Test
    public void createFile01()
    {
        File file;
        try {
            //linux下面 file = new File("/home/joshua317/file/test1.txt");
            file = new File("E:\\java\\test1.txt");
            file.createNewFile();

            System.out.println(file.getName());
            System.out.println(file.length());
            System.out.println(file.getParent());
            System.out.println(file.getPath());
            System.out.println(file.getUsableSpace());
            System.out.println(file.getTotalSpace());
            System.out.println(file.getFreeSpace());
            System.out.println(file.getAbsoluteFile());
            System.out.println(file.getAbsolutePath());
            System.out.println(file.getCanonicalFile());
            System.out.println(file.getCanonicalPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void createFile02()
    {
        File file;
        try {
            //linux下面 file = new File("/home/joshua317/file/", "test2.txt");
            file = new File("E:\\java\\", "test2.txt");
            file.createNewFile();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Test
    public void createFile03()
    {
        File fileParent, file;
        try {
            //linux下面 fileParent = new File("/home/joshua317/file/");
            fileParent = new File("E:\\java\\");
            file = new File(fileParent, "test3.txt");
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Test
    public void createFile04()
    {
        File file;
        try {
            //linux下面 fileParent = new File("file:/home/joshua317/file/test4.txt");
            URI uri=new URI("file:///E:/java/test4.txt");
            file = new File(uri);
            file.createNewFile();
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        }
    }
}

注意:

new File 只是创建了一个File对象,还需要调用createNewFile()方法才能实现文件的创建

//当且仅当不存在具有此抽象路径名指定的名称的文件时,原子地创建由此抽象路径名指定的一个新的空文件。
public boolean createNewFile()

返回:会自动检查文件是否存在,如果不存在则创建文件。
抛出异常:IOException :IO异常;SecurityException:SecurityManager.checkWrite(java.lang.String)方法拒绝对文件的写访问

 

posted @ 2022-02-25 23:48  joshua317  阅读(961)  评论(0编辑  收藏  举报