文件的操作

package zmx_demo;

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

/**
 * File常用的方法
 * 1.文件名
 * getName():文件名
 * gerPath():路径名
 * getAbsoluteFile()绝对路径所对应的File对象
 * getAbsolutePath()绝对路径名
 * getParent()父目录,相对路径的父目录,可能是null
 * 2、判断信息
 * exists()
 * canWrite()
 * canRead(()
 * isFile()
 * isDirectory()
 * isAbsolute():消除平台差异,ie以盘符开头,其他以/开头
 * 3、长度
 * length()  it's byte number
 * 4.create  and  delete
 * createNewFile() not exist File create New File
 * delete()  delete File
 * static createTempFile(prefix:3 bytes,suffix is .temp)default temporary space
 * deleteOnExit()  exit virtual machine delete,always usr for delete temporary space
 */

public class demo1 {
    public static void main(String[] args) {
        try {
            test2();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
    public static void test1(){
        System.out.println(File.separator);//打印路径分割符
        System.out.println(File.pathSeparator);//打印语句分割符
        String path="F:"+File.separator+"xp"+"2.jpg";
        //File src=new File(path);//构建绝对路径
        File src=new File("F:","xp"+File.separator+"2.jpg");//构建相对路径
        File des=new File("text.txt");//没有盘符,以user.dir构建   相对路径

        System.out.println(src.getName());//打印文件的名字
        System.out.println(src.getPath());//打印文件的绝对路径
        System.out.println(des.getPath());//看不到绝对路径因为他是相对路径
        System.out.println(src.getParent());//得看是怎么构建的了。如果是当前项目的相对就是null
        System.out.println(des.getAbsolutePath());//可以看到绝对路径
    }
    public static void test2() throws IOException, InterruptedException {
        String path="F:"+File.separator+"xp"+"2.jpg";
        //File src=new File(path);//构建绝对路径
        File src=new File("F:","xp"+File.separator+"2.jpg");//构建相对路径
        System.out.println("文件是否存在:"+src.exists());
        System.out.println("文件是否可写:"+src.canWrite());
        System.out.println("if file canWrite:"+src.canWrite());
        //if it's File or Directory
        if(src.isFile()){
            System.out.println("File");
        }
        else{
            System.out.println("Directory");//if File is not exist,it's Directory
        }
        System.out.println("if it's Absolute:"+src.isAbsolute());
        System.out.println("byte length:"+src.length());  //only File could read his own length
        File temp=File.createTempFile("test",".temp",new File("F:"+File.separator+"xp"));
        Thread.sleep(10000);
        temp.deleteOnExit();

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值