public class CreateNewFileDemo {
public static void main(String[] args) throws IOException {
/**
* 在当前项目目录下新建一个test.txt
/
File file=new File("./test.txt");
/*
* boolean exists()
* 判断当前的File表示的文件或者目录是否已经存在,存在返回true
*/
if(!file.exists()) {
file.createNewFile();
System.out.println(“文件已创建”);
}
else {
System.out.println(“文件已存在”);
}
}
}
import java.io.File;
/**
- java.io.File
- File用于表示文件系统中的一个文件或目录
- 使用File我们可以:
- 1:访问其表示的文件或目录的属性(名字,大小等)
- 2:创建,删除文件或者目录
- 3:访问一个目录中的子项
- 但不能访问文件数据
- @author Lemon
/
public class FileDemo {
public static void main(String[] args) {
/*
* 创建File是要指定路径
* 路径有两种:绝对路径和相对路径
* 绝对路径通常不适用,虽然清晰明了,但是无法跨平台
*
* 相对路径不能直接体现出实际位置,但是灵活并适用各种不同的运行环境
* 在eclipse中执行代码时,"./"表示当前目录指的是当前项目目录
/
File file=new File("./demo.txt");
//获取文件名
String name=file.getName();
System.out.println(name);
//获取文件长度
long length=file.length();
System.out.println(length);
//获取绝对路径
String path=file.getAbsolutePath();
System.out.println(path);
/*
* 是否可读,可写,是否为隐藏文件
*/
boolean cr=file.canRead();
boolean cw=file.canWrite();
boolean ih=file.isHidden();
System.out.println(“可读:”+cr);
System.out.println(“可写:”+cw);
System.out.println(“隐藏文件:”+ih);
}
}