IOUtil

简介: 111

注意:所有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.递归某目录下全部文件

/**
  * 获取路径下的所有文件/文件夹
  * @param directoryPath 目标路径(父级,
  * 如遍历:
  * 文件夹1
  *   文件1
  *   文件夹2
  *       文件2
  * 则写文件夹1全路径即可
  )
  * @param list          返回路径的集合
  */
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);
            }
        }
    }
}
相关文章
|
3月前
|
SQL 监控 机器人
|
3月前
|
前端开发 数据安全/隐私保护
|
3月前
|
存储 缓存 Java
|
3月前
|
安全 Java 数据安全/隐私保护
|
3月前
|
Java 开发工具 Maven
|
3月前
|
自然语言处理 fastjson Java
|
3月前
|
运维 Devops 开发工具
|
3月前
|
Java 测试技术 Linux
|
3月前
|
jenkins Java 持续交付
|
3月前
|
JSON 数据格式

热门文章

最新文章