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();
}
}
文件的操作
最新推荐文章于 2024-11-27 14:53:15 发布
6309

被折叠的 条评论
为什么被折叠?



