01.文件处理
# 01.基本操作
# 1.1 Java File文件处理
java.io
包中的File
类,使我们可以处理文件。
要使用File
类,需要创建该类的对象,然后指定文件名或目录名称:
例如:
import java.io.File; // 导入File类
File myObj = new File("filename.txt"); // 指定filename
2
3
File
类具有许多有用的方法来创建和获取有关文件的信息。
# 1.2 File类创建相关方法
createNewFile()
:在指定位置创建一个空文件,成功就返回true,如果已存在就不创建,然后返回false。
mkdir()
:在指定位置创建一个单级文件夹。
mkdirs()
:在指定位置创建一个多级文件夹。
renameTo(File dest)
:如果目标文件与源文件是在同一个路径下,那么renameTo的作用是重命名, 如果目标文件与源文件不是在同一个路径下,那么renameTo的作用就是剪切,而且还不能操作文件夹。
# 1.3 File类删除相关方法
delete()
:删除文件或者一个空文件夹,不能删除非空文件夹,马上删除文件,返回一个布尔值。
deleteOnExit()
:jvm退出时删除文件或者文件夹,用于删除临时文件,无返回值。
# 1.4 File类判断相关方法
exists()
:文件或文件夹是否存在。
isFile()
:是否是一个文件,如果不存在,则始终为false。
isDirectory()
: 是否是一个目录,如果不存在,则始终为false。
isHidden()
:是否是一个隐藏的文件或是否是隐藏的目录。
isAbsolute()
: 测试此抽象路径名是否为绝对路径名。
# 1.5 File类获取相关方法
getName()
:获取文件或文件夹的名称,不包含上级路径。
getAbsolutePath()
:获取文件的绝对路径,与文件是否存在没关系
length()
:获取文件的大小(字节数),如果文件不存在则返回0L,如果是文件夹也返回0L。
getParent()
:返回此抽象路径名父目录的路径名字符串;如果此路径名没有指定父目录,则返回null。
lastModified()
:获取最后一次被修改的时间。
# 1.6 File类文件夹相关方法
static File[] listRoots()
:列出所有的根目录(Window中就是所有系统的盘符)
list()
:返回目录下的文件或者目录名,包含隐藏文件。对于文件这样操作会返回null。
listFiles()
:返回目录下的文件或者目录对象(File类实例),包含隐藏文件。对于文件这样操作会返回null。
list(FilenameFilter filter)
:返回指定当前目录中符合过滤条件的子文件或子目录。对于文件这样操作会返回null。
listFiles(FilenameFilter filter)
:返回指定当前目录中符合过滤条件的子文件或子目录。对于文件这样操作会返回null。
# 1.7 基本使用演示
import java.io.File;
import java.io.IOException;
public class Test{
public static void main(String[] args) throws IOException {
File fileCreate = new File("F:\\cjavapy\\files\\file.txt");
// 创建单级文件夹
System.out.println("单级文件夹创建:" + fileCreate.mkdir());
// 创建多级文件夹
System.out.println("多级文件夹创建:" + fileCreate.mkdirs());
// 创建文件
System.out.println("创建文件:" + fileCreate.createNewFile());
// 文件重命名
File toFile = new File("F:\\cjavapy\\files\\toFile.txt");
System.out.println("文件重命名:" + fileCreate.renameTo(toFile));
// 删除方法
File file = new File("F:\\cjavapy\\files\\toFile.tx");
System.out.println("删除文件:" + file.delete());
file.deleteOnExit();
// 判断方法
/*
* File file = new File("F:\\cjavapy.txt");
* System.out.println("文件或者文件夹存在吗?"+file.exists());
* System.out.println("是一个文件吗?"+file.isFile());
* System.out.println("是一个文件夹吗?"+file.isDirectory());
* System.out.println("是隐藏文件吗?"+file.isHidden());
* System.out.println("此路径是绝对路径名?"+file.isAbsolute());
*/
// 获取方法
/*
* File file = new File("f:\\cjavapy.txt");
* System.out.println("文件或者文件夹得名称是:"+file.getName());
* System.out.println("绝对路径是:"+file.getPath());
* System.out.println("绝对路径是:"+file.getAbsolutePath());
* System.out.println("文件大小是(以字节为单位):"+file.length());
* System.out.println("父路径是"+file.getParent()); //使用日期类与日期格式化类进行获取规定的时间 long
* lastmodified= file.lastModified(); Date data = new Date(lastmodified);
* SimpleDateFormat simpledataformat = new
* SimpleDateFormat("YY年MM月DD日 HH:mm:ss");
* System.out.println("最后一次修改的时间是:"+simpledataformat.format(data));
*/
// 文件或者文件夹的方法
/*
* File[] file = File.listRoots(); System.out.println("所有的盘符是:"); for (File item
* : file) { System.out.println("\t" + item); } File filename = new
* File("F:\\cjavapy"); String[] name = filename.list();
* System.out.println("指定文件夹下的文件或者文件夹有:"); for (String item : name) {
* System.out.println("\t" + item); } File[] f = filename.listFiles();
* System.out.println("获得该路径下的文件或文件夹是:"); for (File item : f) {
* System.out.println("\t" + item.getName()); }
*/
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# 02.创建和写文件
# 2.1 创建文件
- 要使用Java创建文件,可以使用
createNewFile()
方法。 - 此方法返回一个布尔值:如果成功创建了文件,则为
true
,如果文件已经存在,则为false
。 - 该方法需要包含在
try ... catch
块中。 - 因为如果发生错误(如果由于某种原因而无法创建文件),则会抛出
IOException
:
package com.case_01;
import java.io.File;
import java.io.IOException;
public class Test{
public static void main(String[] args) throws IOException {
try {
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- 要在特定目录中创建文件(需要权限),需要指定文件的路径,并使用双反斜杠转义“
\
”字符(对于Windows)。 - 在Mac和Linux上,只需编写路径即可,例如:
/Users/cjavapy/filename.txt
例如:
File myObj = new File("C:\\Users\\cjavapy\\filename.txt");
# 2.2 写文件
- 写文件使用
FileWriter
类及其write()
方法,将一些文本写入我们在上面的示例中创建的文件中。 - 完成写入文件后,注意应使用
close()
方法将其关闭
package com.case_01;
import java.io.FileWriter; // 导入FileWriter
import java.io.IOException; // 导入IOException
public class Test{
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("http://www.cjavapy.com");
myWriter.close();
System.out.println("Successfully");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 2.3 追加到文件尾部
package com.case_01;
import java.io.*;
import java.util.Scanner; // 导入Scanner类读取文本文件
public class Test {
public static void appendMethodB(String fileName, String content) {
try {
//打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
FileWriter writer = new FileWriter(fileName, true);
writer.write(content);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String fileName = "D:\\myproject\\filename.txt";
//按方法B追加文件
Test.appendMethodB(fileName, "append end. \n");
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 03.读文件
# 3.1 基本读文件
package com.case_01;
import java.io.File; // 导入File
import java.io.FileNotFoundException; // 处理错误异常
import java.util.Scanner; // 导入Scanner类读取文本文件
public class Test{
public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 3.2 获取文件信息
package com.case_01;
import java.io.File; // 导入File
public class Test{
public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.exists()) {
System.out.println("File name: " + myObj.getName()); // File name: filename.txt
System.out.println("Absolute path: " + myObj.getAbsolutePath()); // Absolute path: D:\myproject\filename.txt
System.out.println("Writeable: " + myObj.canWrite()); // Writeable: true
System.out.println("Readable " + myObj.canRead()); // Readable true
System.out.println("File size in bytes " + myObj.length()); // File size in bytes 59
} else {
System.out.println("The file does not exist.");
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 3.3 读取文件示例代码
package com.case_01;
import java.io.*;
import java.util.Scanner; // 导入Scanner类读取文本文件
public class Test {
// 1、以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
public static void readFileByBytes(String fileName) {
File file = new File(fileName);
InputStream in = null;
try {
System.out.println("以字节为单位读取文件内容,一次读一个字节:");
// 一次读一个字节
in = new FileInputStream(file);
int tempbyte;
while ((tempbyte = in.read()) != -1) {
System.out.write(tempbyte);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
System.out.println("以字节为单位读取文件内容,一次读多个字节:");
// 一次读多个字节
byte[] tempbytes = new byte[100];
int byteread = 0;
in = new FileInputStream(fileName);
Test.showAvailableBytes(in);
// 读入多个字节到字节数组中,byteread为一次读入的字节数
while ((byteread = in.read(tempbytes)) != -1) {
System.out.write(tempbytes, 0, byteread);
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
}
}
// 2、以字符为单位读取文件,常用于读文本,数字等类型的文件
public static void readFileByChars(String fileName) {
File file = new File(fileName);
Reader reader = null;
try {
System.out.println("以字符为单位读取文件内容,一次读一个字节:");
// 一次读一个字符
reader = new InputStreamReader(new FileInputStream(file));
int tempchar;
while ((tempchar = reader.read()) != -1) {
// 对于windows下,\r\n这两个字符在一起时,表示一个换行。
// 但如果这两个字符分开显示时,会换两次行。
// 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
if (((char) tempchar) != '\r') {
System.out.print((char) tempchar);
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println("以字符为单位读取文件内容,一次读多个字节:");
// 一次读多个字符
char[] tempchars = new char[30];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(fileName));
// 读入多个字符到字符数组中,charread为一次读取字符数
while ((charread = reader.read(tempchars)) != -1) {
// 同样屏蔽掉\r不显示
if ((charread == tempchars.length)
&& (tempchars[tempchars.length - 1] != '\r')) {
System.out.print(tempchars);
} else {
for (int i = 0; i < charread; i++) {
if (tempchars[i] == '\r') {
continue;
} else {
System.out.print(tempchars[i]);
}
}
}
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
// 3、 以行为单位读取文件,常用于读面向行的格式化文件
public static void readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
// 4、随机读取文件内容
public static void readFileByRandomAccess(String fileName) {
RandomAccessFile randomFile = null;
try {
System.out.println("随机读取一段文件内容:");
// 打开一个随机访问文件流,按只读方式
randomFile = new RandomAccessFile(fileName, "r");
// 文件长度,字节数
long fileLength = randomFile.length();
// 读文件的起始位置
int beginIndex = (fileLength > 4) ? 4 : 0;
// 将读文件的开始位置移到beginIndex位置。
randomFile.seek(beginIndex);
byte[] bytes = new byte[10];
int byteread = 0;
// 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
// 将一次读取的字节数赋给byteread
while ((byteread = randomFile.read(bytes)) != -1) {
System.out.write(bytes, 0, byteread);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (randomFile != null) {
try {
randomFile.close();
} catch (IOException e1) {
}
}
}
}
// 5、显示输入流中还剩的字节数
private static void showAvailableBytes(InputStream in) {
try {
System.out.println("当前字节输入流中的字节数为:" + in.available());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String fileName = "D:\\myproject\\filename.txt";
Test.readFileByBytes(fileName);
Test.readFileByChars(fileName);
Test.readFileByLines(fileName);
Test.readFileByRandomAccess(fileName);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# 04.删除文件
# 4.1 删除文件
- 要使用Java删除文件,请使用
delete()
方法:
package com.case_01;
import java.io.*;
public class Test {
public static void main(String[] args) {
File myObj = new File("D:\\myproject\\filename.txt");
if (myObj.delete()) {
System.out.println("Deleted the file: " + myObj.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
# 4.2 删除文件夹
- 除了能删除文件,也可以删除文件夹。但是,删除的文件夹必须为空
import java.io.*;
public class Test {
public static void main(String[] args) {
File myObj = new File("D:\\myproject\\day03\\src\\com\\example02");
if (myObj.delete()) {
System.out.println("Deleted the folder: " + myObj.getName());
} else {
System.out.println("Failed to delete the folder.");
}
}
}
2
3
4
5
6
7
8
9
10
11
12
# 4.3 删除目录及所有文件
- 删除某个目录及目录下的所有子目录和文件。
- File.delete()只能删除某个文件或者空目录,要想要删除某个目录及其所有子文件和子目录,要使用递归进行删除。
import java.io.*;
public class Test {
public static boolean delFiles(File file){
boolean result = false;
//目录
if(file.isDirectory()){
File[] childrenFiles = file.listFiles();
for (File childFile:childrenFiles){
result = delFiles(childFile);
if(!result){
return result;
}
}
}
//删除 文件、空目录
result = file.delete();
return result;
}
public static void main(String[] args) {
File file = new File("D:\\myproject\\day03\\src\\com\\example01");
System.out.println("result:"+delFiles(file));
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25