Java创建文件的三种方法

public class FileCreate {

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

    /**
     * 文件创建方式1
     * 绝对路径创建文件
     */
    @Test
    public void create1() {
        String filePath = "D:\\news1.txt";
        File file = new File(filePath);
        try {
            file.createNewFile();
            System.out.println("create1文件创建成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 文件创建方式2
     * 根据父目录+子路径创建
     */
    @Test
    public void create2() {
        String filePath = "D:\\";
        File parentPath = new File(filePath);
        String filename = "news2.txt";
        File file = new File(parentPath, filename);
        try {
            file.createNewFile();
            System.out.println("create2文件创建成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 文件创建方式3
     * 根据父目录+子路径创建
     */
    @Test
    public void create3() {
        String parentPath = "D:\\";
        String filename = "news3.txt";
        File file = new File(parentPath, filename);
        try {
            file.createNewFile();
            System.out.println("create3文件创建成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
posted @ 2022-08-06 20:38  jarico  阅读(821)  评论(0)    收藏  举报