文件操作
1、 建立文件
File uf1 = new File("user1.txt");
System.out.println(uf1.createNewFile());
2、删除文件
if(uf1.exists()) uf1.delete();
if(uf2.exists()) uf2.deleteOnExit();
3.列出目录下的所有文件
File dir = new File("c:/javaok");
if(dir.exists()) {
File[] fs = dir.listFiles();
for(File t : fs) {
if(t.isFile() && t.getName().endsWith(".rar")) {
t.delete();
}
}
}
4、统计文件代码行数,空行数
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class File5 {
static int num = 0;
public static void main(String[] args) throws FileNotFoundException {
String path = "D:\\eclipse-workspace\\part02\\src\\cn\\Bin2.java";
BufferedReader br = new BufferedReader(new FileReader(path));
System.out.println(br.lines().filter(e->e.trim().length()>0).count());
}
}
5、递归统计文件个数及文件行数实现
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class File4 {
static int num = 0;
static int rows = 0;
static int space = 0;
public static void main(String[] args) throws Exception {
String path = "c:/javaok";
count(new File("d:/eclipse-workspace"));
System.out.printf("%s 共有%d个java程序文件%n","d:/eclipse-workspace",num);
System.out.printf("共 %d 行代码%n",rows);
System.out.printf("共 %d 空行代码%n",space);
}
public static void count(File dir) throws FileNotFoundException {
if (dir.isDirectory()) {
File[] f = dir.listFiles();
for (File t : f) {
if (t.isDirectory())
count(t);
if (t.isFile() && t.getName().endsWith(".java")) {
++num;
BufferedReader br = new BufferedReader(new FileReader(t));
rows+=br.lines().count();
BufferedReader br2 = new BufferedReader(new FileReader(t));
space+=br2.lines().filter(e->e.trim().length()==0).count();
}
}
}
if (dir.isFile() && dir.getName().endsWith(".rar")) {
++num;
BufferedReader br = new BufferedReader(new FileReader(dir));
rows+=br.lines().count();
BufferedReader br2 = new BufferedReader(new FileReader(dir));
space+=br2.lines().filter(e->e.trim().length()==0).count();
}
}
public static void del(File dir) {
if (dir.isDirectory()) {
File[] f = dir.listFiles();
for (File t : f) {
if (t.isDirectory())
del(t);
if (t.isFile() && t.getName().endsWith(".rar"))
t.delete();
}
}
if (dir.isFile() && dir.getName().endsWith(".rar"))
dir.delete();
}
}