常用工具类---IOUtils
本文涉及的产品
应用实时监控服务-可观测链路OpenTelemetry版,每月50GB免费额度
应用实时监控服务-用户体验监控,每月100OCU免费额度
简介:
该文档是关于Java中文件操作的说明,强调所有IO操作必须在`finally`块中关闭。提供了三个示例:1) 读取指定文件`test.txt`的全部内容,使用`FileReader`和`StringBuffer`;2) 追加内容到`test.txt`文件,通过`FileOutputStream`, `OutputStreamWriter`和`BufferedWriter`实现;3) 递归遍历目录下的所有文件,使用`File`类和递归函数获取每个文件的绝对路径。
注意:所有IO操作均需在finally中手动关闭
1.读取指定文件内全部内容
String path = File.separator + "app" + File.separator + "test.txt";
File file = new File(path);
reader = new FileReader(file);
char[] bb = new char[1024];
StringBuffer allUploadFilePath = new StringBuffer();
int n;
while ((n = reader.read(bb)) != -1) {
allUploadFilePath.append(new String(bb, 0, n));
}
2.追加内容到指定文件
FileOutputStream fileOutputStream = null;
OutputStreamWriter outputStreamWriter = null;
BufferedWriter bufferedWriter = null;
File file = new File("D:/test.txt");
fileOutputStream = new FileOutputStream(file, true);
outputStreamWriter = new OutputStreamWriter(fileOutputStream);
bufferedWriter = new BufferedWriter(outputStreamWriter);
for (String conent : allFilePath) {
bufferedWriter.write("," + conent);
}
3.递归某目录下全部文件
public static void readfile(String directoryPath, List<String> list) {
File file = new File(directoryPath);
if (!file.isDirectory()) {
list.add(file.getAbsolutePath());
} else if (file.isDirectory()) {
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
File readfile = new File(directoryPath + File.separator + filelist[i]);
if (!readfile.isDirectory()) {
list.add(readfile.getAbsolutePath());
} else if (readfile.isDirectory()) {
readfile(readfile.getAbsolutePath(), list);
}
}
}
}