一、文件操作
1.文件的概念
文件是计算机中一种基本的数据存储形式, 每个文件以一个文件路径和文件名称进行表示,在需要访问该文件的时,只需要知道该文件的路径以及文件的全名即可。在不同的操作系统环境下,文件路径的表示形式是不一样的,例如在Windows操作系统中一般的表示形式为C:\windows\system,而Unix上的表示形式为/user/my。
2.绝对路径与相对路径
绝对路径是指书写文件的完整路径,例如d:\java\Hello.java,该路径中包含文件的完整路径d:\java以及文件的全名Hello.java。使用该路径可以唯一的找到一个文件,不会产生歧义。但是使用绝对路径在表示文件时,受到的限制很大,且不能在不同的操作系统下运行,因为不同操作系统下绝对路径的表达形式存在不同。
相对路径是指书写文件的部分路径,例如\test\Hello.java,该路径中只包含文件的部分路径\test和文件的全名Hello.java,部分路径是指当前路径下的子路径,例如当前程序在d:\abc下运行,则该文件的完整路径就是d:\abc\test。使用这种形式,可以更加通用的代表文件的位置,使得文件路径产生一定的灵活性。
3.File类基本使用方法
3.1字段摘要
public class TestFileFiled {
public static void main(String[] args) {
String pathseparator = File.pathSeparator;
System.out.println(pathseparator);
char pathseparator2 = File.pathSeparatorChar;
System.out.println(pathseparator2);
String separator = File.separator;
System.out.println(separator);
char separator2 = File.separatorChar;
System.out.println(separator2);
}
}
输出结果为
;
;
/
/
3.2方法摘要
public class TestFileMethod {
private File file = null;
public TestFileMethod(String path) {
file = new File(path);
if (file.exists()) {
System.out.println("文件存在");
System.out.println("绝对路径:" + file.getAbsolutePath());
System.out.println("相对路径:" + file.getPath());
System.out.println("文件名" + file.getName());
} else {
System.out.println("文件不存在");
}
}
public static void main(String[] args) {
// new TestFileMethod("C:\\Users\\Administrator\\Desktop\\xxx.txt");
//new TestFileMethod("C:/Users/Administrator/Desktop/xxx.txt");
//相对eclipse根目录的相对路径
new TestFileMethod2("xxx.txt");
}
}
3.3文件搜索
3.3.1功能说明:在path路径中搜索包含key关键字的文件个数和文件夹个数。
3.3.2代码实现
public class FileSearchService {
int folderNum = 0;// 文件夹数目
int fileNum = 0;
List<String> filesList = new ArrayList<String>();
public FileSearchService(String path, String key) {
searchKeys(path, key);
//纯文本的多行显示区域
JTextArea jTextArea = new JTextArea();
for (int i = 0; i < filesList.size(); i++) {
String string = filesList.get(i);
jTextArea.append(string + "\n\r");
}
}
public void searchKeys(String path, String key) {
File file = new File(path);
if (file.exists()) {
if (file.isDirectory()) {
// 如果是文件夹
folderNum++;
File[] listFiles = file.listFiles();//
for (int i = 0; i < listFiles.length; i++) {
File file2 = listFiles[i];
searchKes(file2.getAbsolutePath(), key);
}
} else {
String name = file.getName();
if (name.contains(key)) {
String absolutePath = file.getAbsolutePath();
// 如果是文件
fileNum++;
filesList.add(absolutePath);
}
}
} else {
return;
}
}
public static void main(String[] args) {
FileSearchService fileSearchService = new FileSearchService(
"E:\\资料安装包\\文档\\课程计划\\机器人\\新建文件夹", "aa");
System.out.println(fileSearchService.fileNum);
System.out.println(fileSearchService.folderNum);
}
}