Java 中操作文件的方法

文件系统是操作系统用于明确存储设备(通常是的是磁盘硬盘等)或分区上的文件的方法和数据结构; 即在存储设备上组织文件的方法.

在 Java 中 java.io.File 类用于操作系统的文件, 提供了包括了创建, 复制, 移动, 删除文件, 创建目录, 判断文件是否存在, 设置读写权限, 所有者, 最后修改时间等操作. 但是读写文件的内容并不使用 File 类.

File 类的构造方法如下:

1. 通过父 File, 以及子文件名创建

public File(File parent, String child) //如果 child 为null 会抛出 NullPointerException

2. 直接通过文件名创建

public File(String pathname)

3.  通过父目录名, 以及子文件名创建

public File(String parent, String child)

4. 通过 URI 创建

public File(URI uri)

创建完成 File 对象后就可以使用对应的方法操作文件对象了. 以下是一些简单的调用示例:

文件是否可写:

File f = new File("xxx.file");
System.out.println("路径: '" + f.getAbsolutePath() + "', 是否可以写入? " + f.canWrite());

创建一个临时文件以及文件是否存在

try {
    File f = File.createTempFile("21yi_", ".temp");
    System.out.println("临时文件路径: " + f.getAbsolutePath());
    System.out.println("文件是否存在: " + f.exists());
    f.deleteOnExit();
} catch (IOException e) {
    System.err.println("Error: " + e.getMessage());
}

判断文件是否存在并删除

File f = new File("D:\\21yi_file.txt");
if (!f.exists()) {
    System.out.println("文件存在否? " + f.exists());
    try {
        if(f.createNewFile()) {
            System.out.println("创建文件成功.");
        } else {
            System.out.println("创建文件失败.");
        }
    } catch (IOException e) {
        System.err.println("ERROR: " + e.getMessage());
    }
}
System.out.println("文件是否存在? " + f.exists());
if (f.exists()) {
    if(f.delete()) {
        System.out.println("删除了文件.");
    } else {
        System.out.println("删除文件失败.");
    }
}
System.out.println("文件是否存在? " + f.exists());

在 Java 中 java.io.Files 提供了一种封装的文件操作静态方法合集:

使用 FIles 复制文件:

System.out.println("从一个 Path 复制到另一个 Path");
Path source = new File("xxx.src").toPath();
Path target = FileSystems.getDefault().getPath("DirName", "xxx.dst");
Path path = Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
System.out.println("从 Path 到 Path: " + path);

参考

  1. Java File 参考手册
  2. Java Files 参考手册   
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值