文件基础知识和创建文件

文件基础知识和创建文件

1. 文件基础知识

什么是文件?

  • 文件对我们来说并不陌生,文件是保存数据的地方,比如大家经常使用的word文档、text文件、excel文件...都是文件。它既可以保存照片,也可以保存视频、声音...

文件流

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

2.创建文件

创建文件对象相关的构造器和方法

构造器

  • new File(String pathname):根据路径构建一个File对象
  • new File(String parent,String child):根据父目录+子路径构建一个File对象
  • new File(File parent,String child):根据父目录文件+子路径构建一个File对象

方法

  • createNewFile():创建新文件

演示创建文件

方式1:new File(String pathname)

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

    }
    @Test
    public void create01(){
        String filePath = "d:\\news1.txt";
        File file = new File(filePath);

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

    }
}

方式2:new File(String parent,String child)

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

    }
    @Test
    public void create02(){
        String parentPath = "d:\\";
        String filePath = "news2.txt";
        File file = new File(parentPath,filePath);

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

 

方式3:new File(File parent,String child)

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

    }
    @Test
    public void create02(){
        File parentFile = new File("d:\\");
        String filePath = "news2.txt";
        File file = new File(parentFile,filePath);

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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值