Java零基础学java之IO流--01创建文件

package com.io_;

import org.junit.Test;

import java.io.File;
import java.io.IOException;

@SuppressWarnings({"all"})
public class FileCreate {
    public static void main(String[] args) {
        /*
        * 创建文件对象相关构造器和方法
        * 1. new File(String pathname) 根据路径构建一个File对象
        * 2. new File(File parent,String child) 根据父目录文件+子路径构建
        * 3. new File(String parent,String child) 根据父目录+子路径构建
        */
    }

    //1. new File(String pathname) 根据路径构建一个File对象
    //1. 定义一个方法(创建文件)
    @Test  //(@Test 注解要写在需要测试的方法上面,这个类不需要new就可以运行)  import org.junit.Test;
    public void creat01() {
        //2. 创建文件路径
        String filePath = "e:\\news1.txt";
        //3. 使用 new File() 方法
        File file = new File(filePath);
        /*
        * 这里的file对象,在java程序中,只是一个对象
        * 只有执行了createNewFile() 方法,才会真正的,在磁盘创建该文件
        */
        //4. 再调用 createNewFile() 方法 创建新文件
        //file.createNewFile();  ctrl + alt + t (try-catch扑捉异常)
        try {
            file.createNewFile();
        System.out.println("文件创建成功!");          //java.io.IOException: 拒绝访问。
        } catch (IOException e) {                   // 右击计算机D盘,打开属性,属性--->安全---->编辑,
            e.printStackTrace();                    //  然后把除完全控制的其他权限增加上,再运行发现可以了
        }
    }
    //2. new File(File parent,String child) 根据父目录文件+子路径构建
    //e:\\news2.txt ---->  File parent -->e:\\
    //                     String child --> news2.txt
    //1. 定义一个方法(创建文件)
    @Test
    public void create02() {
        //2. new一个父目录对象
        File parentFile = new File("e:\\");
        //3. 定义一个子路径
        String fileName = "news2.txt";
        //4. 使用 new File() 方法
        File file = new File(parentFile, fileName);
        //5. 调用createNewFile() 方法
        try {
            file.createNewFile();
            System.out.println("创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 3. new File(String parent,String child) 根据父目录+子路径构建
    //1. 定义一个方法(创建文件)
    @Test
    public void create03() {
        //2. 定义一个父目录
        String parentPath = "e:\\";
        //3. 定义一个子路径
        String fileName = "news3.txt";
        // 4. 调用new File() 方法
        File file = new File(parentPath, fileName);
        //5. 调用createNewFile() 方法
        try {
            file.createNewFile();
            System.out.println("文件创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值