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\test\2.jpg //绝对路径 src = new File("E:/xp/test/2.jpg"); System.out.println(src.getName()); //2.jpg System.out.println(src.getPath()); //E:\xp\test\2.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 10\java300\test.txt } }
几种获取文件名经常使用的方法:java
getName():返回名称windows
getPath():若是是绝对路径,返回完整路径,不然相对路径spa
getAbsolutePath():返回绝对路径code
getParent():返回上一级目录,若是是相对,返回null对象
判断信息方法:blog
exists():文件是否存在,boolean型ip
canWriter():文件是否可写 ,booleanget
canRead():文件是否可读 it
isFile():是文件仍是文件夹,不存在默认为文件夹io
isDirectory():是否为目录
isAbsolute():是否为绝对路径
判断长度:
length():字节数,若是是文件夹长度为0,不能读取,只有文件的长度能读取
建立和删除文件:
createNewFile():建立文件 boolean类型
delete():删除文件