Java文件操作-Java.IO File操作

import java.io.File;

public class File_2_OperateDemo {
    public static void main(String[] argv) throws Exception {
        //创建文件。默认在应用程序根目录下生成test.txt文件,若文件已生成不会覆盖
        File dummyFile = new File("test.txt");
        boolean fileCreated = dummyFile.createNewFile();
        System.out.print("\r\n 文件生成结果:" + fileCreated + ";文件生成路径:" + dummyFile.getAbsolutePath());

        //创建临时文件。创建临时文件用于文件路径权限敏感的情况
        File tempFile = File.createTempFile("abc", ".txt");
        System.out.print("\r\n 文件生成路径:" + tempFile.getAbsolutePath());

        //创建文件路径。
        File newDir = new File("C:\\test");
        boolean dirCreated = newDir.mkdir();
        System.out.print("\r\n 文件路径创建结果:" + dirCreated);

        //文件重命名。
        File oldFile = new File("old_dummy.txt");
        File newFile = new File("new_dummy.txt");
        boolean fileRenamed = oldFile.renameTo(newFile);
        if (fileRenamed) {
            System.out.println("\r\n 文件重命名结果:" + oldFile + "  renamed  to " + newFile + "  success.");
        } else {
            System.out.println("\r\n 文件重命名结果: Renaming " + oldFile + "  to " + newFile + "  failed.");
        }

        //文件重命名,文件必须真实存在。
        fileCreated = oldFile.createNewFile();
        if (fileCreated || oldFile.exists()) {
            //若目标文件已经存在,则重命名不会成功,所以若存在需要先删除。
            if (newFile.exists()) newFile.delete();
            boolean renamedFlag = oldFile.renameTo(newFile);
            if (!renamedFlag) {
                System.out.println("Could not  rename  " + oldFile);
            }
            System.out.println("\r\n 文件重命名结果: Renaming " + oldFile + "  to " + newFile
                    + "  success.");
        }

        //获取文件长度。length()方法(以字节为单位),如果File对象表示不存在的文件,则length()方法返回零
        File myFile = new File("myfile.txt");
        long fileLength = myFile.length();
        System.out.println("\r\n 文件长度: " + fileLength);
    }
}

参考:

https://www.w3cschool.cn/java/java-io-file-operation.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值