Java——IO之常量及路径

package com.io.demo;

import java.io.File;

/*
 * 两个常用常量
 * 路径分隔符  ; File.pathSeparator
 * 名称分隔符   windows下:   非windows下:/
 * 
 * 相对路径与绝对路径构造File对象
 * */
public class IOFile {
    public static void main(String[] args) {
        System.out.println(File.pathSeparator);  // ;
        System.out.println(File.separator); //  
        //路径表示形式1,因为转义字符的原因,要用双斜杠
        String path    ="E:\soft\book\1.txt";
        //路径表示形式2,可以做跨平台
        path="E"+File.separator+"soft"+File.separator+"book"+File.separator+"1.txt";
        //路径表示形式3,推荐
        path="E:/soft/book/1.txt";
        
        
        String parentPath="E:/xp/test";
        String name = "2.jpg";
        
        //相对路径
        File src = new File(parentPath,name);
        src = new File(new File(parentPath),name);
        
        System.out.println(src.getName());  //2.jpg
        System.out.println(src.getPath());    //E:xp	est2.jpg
        
        
        //绝对路径
        src = new File("E:/xp/test/2.jpg");
        System.out.println(src.getName());  //2.jpg
        System.out.println(src.getPath());    //E:xp	est2.jpg
        
        //没有盘符,以user.dir构建
        src = new File("test.txt");
        System.out.println(src.getName());  //test.txt
        System.out.println(src.getPath());    //test.txt
        System.out.println(src.getAbsolutePath()); //D:MyEclipse 10java300	est.txt
    }    
}

 几种获取文件名常用的方法:

  getName():返回名称

  getPath():如果是绝对路径,返回完整路径,否则相对路径

  getAbsolutePath():返回绝对路径

  getParent():返回上一级目录,如果是相对,返回null

判断信息方法:

  exists():文件是否存在,boolean型

  canWriter():文件是否可写 ,boolean

  canRead():文件是否可读 

  isFile():是文件还是文件夹,不存在默认为文件夹

  isDirectory():是否为目录

  isAbsolute():是否为绝对路径

判断长度:

  length():字节数,如果是文件夹长度为0,不能读取,只有文件的长度能读取

创建和删除文件:

  createNewFile():创建文件  boolean类型

  delete():删除文件

原文地址:https://www.cnblogs.com/liurg/p/8297174.html