【Java】File文件操作

1.  Java API 文档Java Platform SE 7 icon-default.png?t=LA92https://docs.oracle.com/javase/7/docs/api/2.  如何构造一个文件 File 对象

// 通过下面几种方式,可以构建一个 file 对象
private static void test1() {
	String path = "C:\\Users\\ghz\\Desktop\\test.txt";
	File f1 = new File(path);
	File f2 = new File("C:\\Users\\ghz\\Desktop");
	File f3 = new File(f2,"test.txt");
	File f4 = new File("C:\\Users\\ghz\\Desktop","test.txt");
	File f5 = new File(URI.create("file:///C:/Users/ghz/Desktop/course/tools/docs_www/api/index.html"));
}

3.  路径分隔符和目录分隔符

// 路径分隔符
System.out.println(File.pathSeparator);
System.out.println(File.pathSeparatorChar);
// 目录分隔符
System.out.println(File.separator);
System.out.println(File.separatorChar);
// 用目录分隔符来实现多平台兼容
File f = new File("C:"+File.separator+"Users"+ File.separator+"ghz"+File.separator+"Desktop"+File.separator+"test.txt");
System.out.println(f.getAbsolutePath());

4. 创建文件、临时文件、目录

// 创建文件
String path = "C:\\Users\\ghz\\Desktop\\test.txt";
File f = new File(path);
if(!f.exists()){
	try {
		boolean b = f.createNewFile();
		if(b)
			System.out.println("创建成功!");
		else
			System.out.println("创建失败!");
	} catch (IOException e) {
		e.printStackTrace();
	}
}

// 创建临时文件
try {
	File f = File.createTempFile("test", ".txt");
	System.out.println(f.getAbsolutePath()); // 打印临时文件地址
} catch (IOException e) {
	e.printStackTrace();
}

// 创建目录
File dir1 = new File("C:\\Users\\ghz\\Desktop\\a");
// 创建一个目录
dir1.mkdir();
File dir2 = new File("C:\\Users\\ghz\\Desktop\\a\\b\\c");
// 递归创建目录
dir2.mkdirs();

5.  遍历文件

// 遍历文件
private static void test4() {
	File f = new File("c:\\");
	File[] files = f.listFiles();
	for(File f1: files){
		System.out.println(f1.getAbsolutePath());
	}
}

// 遍历文件时添加一个过滤器,使用 FileFilter 类,重载 accept() 方法
private static void test4() {
	File f = new File("c:\\");
	File[] files = f.listFiles(new FileFilter(){
		@Override
		public boolean accept(File f) {
			return f.isDirectory();
		}
	});
	for(File f1: files){
		System.out.println(f1.getAbsolutePath());
	}
}

6. 文件的路径

private static void test5() {
	File f = new File(".\\test.txt");
	System.out.println(f.getPath()); // 构造方法中的路径
	System.out.println(f.getAbsolutePath()); // 当前路径+构造方法路径
	try {
		System.out.println(f.getCanonicalPath()); // 规范的绝对路径
	} catch (IOException e) {
		e.printStackTrace();
	}
}

7. 文件属性

private static void test6() {
	String path = "C:\\Users\\ghz\\Desktop\\test.txt";
	File f = new File(path);	
	f.setReadOnly();	// 设置只读	
	System.out.println("能读:"+f.canRead());
	System.out.println("能写:"+f.canWrite());
	System.out.println("能执行:"+f.canExecute());		
	System.out.println(f.getTotalSpace());
	System.out.println(f.getFreeSpace());		
}

猜你喜欢

转载自blog.csdn.net/xiaoyu_wu/article/details/121688816