In java, we use the java.io.File class to implement operations on the basic attributes of files, including reading file attributes, creating files, deleting files, adding files, and so on. File is a class, so you need to create an object when you use it, but the instance of the File class is immutable, that is, once created, the abstract path name represented by the File object will never change, that is to say, using the constructor method, specify the path name, file name, etc. to construct the object of the File class, and then call the createNewFile() method of the object to create the corresponding file.
The object of the File class can represent a specific file path. In practical applications, either an absolute path or a relative path can be used. The following is an instance of creating a file object.
Construction method | illustrate |
---|---|
new File(“d:\test\test.txt”) | Create a file in the specified directory, if the path does not exist, create a virtual file object |
new File(“test.txt”) | Create a file test.txt in the root directory of the current project |
new File(“d:\test”) | test can be a directory or a file |
new File(“d:\test\”,“test.dat”) | Create the specified file in the specified directory |
method | illustrate |
---|---|
File.delete() | delete file or empty directory folder directory |
File.createNewFile() | Create a new empty file |
File.mkdir() | Create a new empty folder |
File.mkdirs() | Create multi-level directories in batches |
File.list() | Get the names of files and folders in the specified directory |
File.listFiles() | Get the file and folder objects in the specified directory |
File.exists() | Whether the file or folder exists |
String getParent() | Returns the pathname string of the parent directory, or null if no parent directory is specified |
File getParentFile() | Return the parent directory File object |
String getName() | Returns the name of a file or folder |
String getAbsolutePath() | get absolute path |
String getPath() | Returns the pathname string |
long lastModified() | Returns the time when the file was last modified |
long length() | Get the length, the number of bytes |
boolean canRead() | Judging whether it is readable |
boolean canWrite() | Determine whether it is writable |
boolean isHidden() | Determine whether to hide |
long getFreeSpace() | Returns the number of unallocated bytes in the partition |
long getTotalSpace() | Returns the partition size of this file |
long getUsableSpace() | Returns the number of bytes occupied |
int hashCode() | file hash code |
method | illustrate |
---|---|
static File[] listRoots() | list available filesystem roots |
boolean renameTo(File dest) | Rename, cut and paste files, move files |
boolean setExecutable(boolean executable) | Set execution permissions |
boolean setExecutable(boolean executable, boolean ownerOnly) | Set execute permissions for all other users |
boolean setLastModified(long time) | set last modified time |
boolean setReadable(boolean readable) | Set read permission |
boolean setReadable(boolean readable, boolean ownerOnly) | Set read permissions for all other users |
boolean setWritable(boolean writable) | Set write permissions |
boolean setWritable(boolean writable, boolean ownerOnly) | Set write permissions for all users |
The immediate parent class of the File class is the Object class. An object of the File class, representing a file or directory on disk. If you forget to write the drive letter path when you create a file or folder, it will be under the project root path by default.
retrieve all files in a directory
public static void count(File f) {
File[] files = f.listFiles();
for (File f1 : files) {
if (f1.isDirectory()) {
count(f1);
}
System.out.printf("文件:%s[%s]%n", f1.getAbsolutePath(), f1.isFile() ? "文件" : "目录");
}
}
delete files in a directory
public static void deltree(File dir) {
if (dir.isDirectory()) {
File[] files = dir.listFiles();
for (File f : files) {
if (f.isDirectory()) {
deltree(f);
}
f.delete();
}
}
dir.delete();
}
Count the number of occurrences of each type of file in the folder.
static Map<String, Integer> map = new HashMap<>();
public static void main(String[] args) {
count1(new File("H:\\weixinProjects"));
System.out.println(map);
}
public static void count1(File f) {
File[] files = f.listFiles();
for (File f1 : files) {
if (f1.isDirectory()) {
count1(f1);
}
if (f1.isFile()) {
String fn = f1.getName().toLowerCase();
String exit = "unknow";
try {
exit = fn.substring(fn.lastIndexOf("."));
} catch (Exception e) {
}
if (map.containsKey(exit)) {
map.put(exit, map.get(exit) + 1);
} else {
map.put(exit, 1);
}
}
}
}
organize files
static Set<String> types = new HashSet<>(List.of("jpg", "png", "webp", "gif", "svg"));
static long num = 0;
public static void count2(File dir, File dst) {
if (!dst.exists()) {
dst.mkdirs();
}
if (dir.isDirectory()) {
File[] files = dir.listFiles();
for (File f : files) {
if (f.isDirectory()) {
count2(f, dst);
}
String fn = f.getName().toLowerCase();
String ext = fn.substring(fn.lastIndexOf(".") + 1);
if (types.contains(ext)) {
copyFile(f, new File(dir, String.format("wx-%03d.%s", ++num, ext)));
}
}
} else {
String fn = dir.getName().toLowerCase();
String ext = fn.substring(fn.lastIndexOf(".") + 1);
copyFile(dir, new File(dir, String.format("wx-%03d.%s", ++num, ext)));
}
}
public static void copyFile(String src, String dst) {
copyFile(new File(src), new File(dst), 8192);
}
public static void copyFile(File src, File dst) {
copyFile(src, dst, 8192);
}
public static void copyFile(File src, File dst, int b) {
try (FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dst)) {
byte[] buf = new byte[b];
int len = 0;
while ((len = fis.read(buf)) >= 0) {
fos.write(buf, 0, len);
}
} catch (Exception e) {
}
}
Write a program to count lines of code
static long AllRows = 0;
static int AllFiles = 0;
public static void main(String[] args) {
count(new File("G:\\javaEE\\Javase\\proa01"));
}
public static void count(File src) {
File[] files = src.listFiles();
for (File f : files) {
if (f.isDirectory()) {
count(f);
}
if (f.getName().endsWith("java")) {
long rows = getRows(f);
AllRows += rows;
AllFiles++;
System.out.println(f.getAbsolutePath() + "[有" + rows + "行]");
System.out.println("总共有" + AllRows);
System.out.println("Java文件有" + AllFiles);
}
}
}
public static long getRows(String src) {
return getRows(new File(src));
}
public static long getRows(File src) {
long rows = 0;
try (var read = new FileInputStream(src)) {
rows = new String(read.readAllBytes()).lines().count();
} catch (Exception e) {
}
return rows;
}