一.Java文件创建
Java文件有三种创建方式
1.1第一种
代码展示:
@Test
public void create01() throws IOException {
String filePath = "e:\\news.txt";
File file = new File(filePath);
file.createNewFile();
}
1.2第二种
代码展示:
@Test
public void create2() throws IOException {
File parentFile = new File("e:\\");
String fileName = "news2.txt";
File file = new File(parentFile, fileName);
file.createNewFile();
}
1.3第三种
代码展示:
@Test
public void create3() throws IOException {
String parentPath = "e:\\";
String fileName = "news3.txt";
File file = new File(parentPath, fileName);
file.createNewFile();
二.获取文件信息
将会用到相关方法:
代码展示:
@Test
public void fileInfo(){
File file = new File("e:\\news.txt");
System.out.println("文件名="+ file.getName());
System.out.println("文件绝对路径:"+file.getAbsolutePath());
System.out.println("文件父目录:"+file.getParentFile());
System.out.println("文件大小:"+file.length());
System.out.println("文件是否存在:"+file.exists());//True
System.out.println("是不是一个文件:"+file.isFile());//T
System.out.println("是不是一个目录:"+file.isDirectory());//F
}
结果展示:
因为news.txt是我们刚刚创建的,所以大小为0,正确
三.小结
1)Java文件创建比较简单,但之前也只知道第一种创建方式,现在系统的了解了一下,并记录下来
2)创建完文件之后,可以对文件有一系列的操作,比如file.getName得到文件名,file.getAbsolutePath得到文件的绝对路径,file.getParent得到文件的父目录,file.lenth得到文件的大小,file.exists判断文件是否存在,file.isFile判断是不是文件,file.isDirectory判断是不是目录等操作