JAVA中文件操作方法和功能

本文介绍了JAVA中文件的基本操作方法,包括文件的创建、重命名、删除等,并提供了具体的代码示例。

JAVA中文件操作方法:

public boolean createNewfile  创建一个新的空文件,其路径名是通过File对象命名的,创建成功则返回TRUE;

public static File createTempFile(String prefix, String suffix) 在系统中临时默认目录中创建一个临时文件。其中prefix

表示前缀不能少于3个字符,suffix表示后缀。如果为NULL则以 .tmp为文件的后缀

demo1:
File file = new File("D:\\test\\Myfile.txt");

if (!file.exists()){
    file.createNewFile();
}
System.out.println("文件路径:" + file.getAbsolutePath());
System.out.println("文件是否可写:" + file.canWrite());

File dir = new File("D:\\test");

if (!dir.exists()){
    dir.mkdir();
}
System.out.println("是否为目录:" + dir.isDirectory());

demo2:

File file = new File("D:\\test\\file.txt");
try {
    boolean b = file.createNewFile();

    if (b){
        System.out.println("已经建立文件:" + file.getAbsolutePath());
    }
    else{
        System.out.println("文件已经存在:" + file.getAbsolutePath());
    }
}catch (IOException e){
    System.out.println("创建文件失败!");
}
3. source.renameTo的用法,文件的重命名
File source = new File("D:\\test\\file.txt");
File target = new File("D:\\test\\rename.txt");
try {
    source.createNewFile();
}catch (IOException e){
    e.printStackTrace();
}
source.renameTo(target);
System.out.println(source.getName() + "已经更名为" + target.getName());

file.txt已经更名为rename.txt

4.文件删除

File target = new File("D:\\test\\rename.txt");

if (b){
    System.out.println("删除文件成功!" + target.getAbsolutePath());
}
else{
    System.out.println("删除文件失败" + target.getAbsolutePath());
}

if (!target.exists()){
    System.out.println("文件不存在" + target.getAbsolutePath());
}
b = target.delete();
if (b){
    System.out.println("删除文件成功1:" + file.getAbsolutePath());
}
else {
    System.out.println("删除文件失败1:" + file.getAbsolutePath());
}
运行结果:
删除文件成功!D:\test\rename.txt
文件不存在D:\test\rename.txt
删除文件失败1:D:\test\file.txt
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值