Overview (java cross-platform performance)
-
The abstract representation of the path names of files and directories. Java encapsulates the files and folders in the computer into the File class. Java operates on files and folders through this class.
-
The File class is a system-independent class, any operating system can use this class
public class File extends Object implements Serializable, Comparable<File>
file: file
directory: directory
path: path
Four static variables in the class:
Modifier and Type | Field and Description |
---|---|
static String |
pathSeparator The system relies on the characters of the path separator, expressed as a convenient string. |
static char |
pathSeparatorChar The system relies on the path separator character. |
static String |
separator The default name separator character that the system relies on, expressed as a convenient string. |
static char |
separatorChar The default name separator character that the system relies on. |
Path separator:
Windows is ";"
Linux is ":"
File name separator:
Windows is "\"
Linux is "/"
Concrete method
import java.io.File;
import java.io.IOException;
/**
* 1.File的构造方法
* 2.File类中的常见方法
*/
public class Demo3 {
public static void main(String[] args) throws IOException {
//1.pathName---真假,绝对相对都行
File file1 = new File("G:\\c.txt");
File file1_1 = new File("G:\\java_file");
System.out.println(file1);
// if (file1.createNewFile()){//创建文件
// System.out.println("原文件不存在,创建成功!");
// }else {
//
// }
// if (file1_1.mkdir()){//创建文件夹
// System.out.println("原文件夹不存在,创建成功!");
// }else {
//
// }
//2.File(String parent, String child)
File file2 = new File("","");
//3.File(File parent, String child)
File file3 = new File(file1,"");
//2.1获取功能
File file2_1 = new File("G:\\");
// System.out.println(file2_1.getTotalSpace());//通过这种抽象路径名返回分区 named大小
// System.out.println(file2_1.getFreeSpace() );//通过这种抽象路径名返回分区中的 named未分配的字节数。
String[] list = file2_1.list();//返回的字符串在该目录下的抽象路径名的文件和目录命名为数组。
// for (int i = 0; i < list.length; i++) {
// System.out.println(list[i]);
// }
File[] files = file2_1.listFiles();//返回表示抽象路径名的目录中的文件的路径名表示抽象的数组。
// for (File filess:files) {
// if (filess.isDirectory()){
// System.out.println("This is a directory");
// }else {
// System.out.println(filess.getAbsoluteFile());
// }
// }
//2.2判断方法————isFile/isDirectory/exists
File file2_2 = new File(file2_1,"Nachos");
// if (file2_2.exists()){
// System.out.println(file2_2.getAbsoluteFile());
// }else {
// file2_2.mkdir();
// }
//2.3创建和删除功能的方法
File file2_3 = new File(file2_2.getAbsolutePath(),"nachos1.txt");
// if (file2_3.createNewFile()){
// System.out.println("创建成功!");
// }
// if (file2_3.exists()){
// if(file2_3.delete()){
// System.out.println("删除成功!");
// }
// }
File file2_4 = new File("H:\\a.txt");
try{
if (file2_4.createNewFile()){
System.out.println("创建成功!");
}else {
System.out.println("创建失败!");
}
}catch (java.io.IOException e){
System.out.println(e.getMessage());
}
}
}