前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >File API

File API

原创
作者头像
HLee
修改2021-08-27 10:58:24
7710
修改2021-08-27 10:58:24
举报
文章被收录于专栏:房东的猫房东的猫

Read文件

代码语言:javascript
复制
@Test
public void readFileLinesToJson() {
    FileUtils.readFileLinesToJson("/mappings/doctorinfo_mapping.json");
}

/**
 * 读取resource文件下的mapping
 * @param filePath
 * @return
 */
public static StringBuffer readFileLinesToJson(String filePath) {

    StringBuffer stringBuffer = new StringBuffer();
    try {
        ClassPathResource classPathResource = new ClassPathResource(filePath);
        InputStream inputStream = classPathResource.getInputStream();

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

        String temp;
        while (null != (temp = bufferedReader.readLine())) {
            stringBuffer.append(temp);
        }
        bufferedReader.close();
        inputStream.close();
    } catch (Exception e) {
        log.debug(e.getMessage());
    }
    return stringBuffer;
}
代码语言:javascript
复制
Java 8逐行读取文件:在此示例中,我将按行读取文件内容并在控制台打印输出。

Path filePath = Paths.get("c:/temp", "data.txt");
//try-with-resources语法,不用手动的编码关闭流
try (Stream<String> lines = Files.lines( filePath )) 
{
    lines.forEach(System.out::println);
} 
catch (IOException e) 
{
    e.printStackTrace();//只是测试用例,生产环境下不要这样做异常处理
}
代码语言:javascript
复制
Java8读取文件,过滤行:我们将文件内容读取为Stream。然后,我们将过滤其中包含单词"password"的所有行。

Path filePath = Paths.get("c:/temp", "data.txt");
try (Stream<String> lines = Files.lines(filePath)){
 
     List<String> filteredLines = lines
                    .filter(s -> s.contains("password"))
                    .collect(Collectors.toList());
      
     filteredLines.forEach(System.out::println);
 
} catch (IOException e) {
    e.printStackTrace();//只是测试用例,生产环境下不要这样做异常处理
}
代码语言:javascript
复制
Java7使用FileReader读取文件:

public static void main(String[] args) {

    // 启动第一个线程
    new Thread(() -> {
        doSomeThing("/Users/Documents/projects/logs/articleId.txt");
    }).start();
 }   
  
private static void doSomeThing(String filenamePath) {
    try {
        FileReader fr = new FileReader(filenamePath);
        BufferedReader bf = new BufferedReader(fr);
        String str;
        while ((str = bf.readLine()) != null) {
            log.info("文章:{}", str);
        }
        bf.close();
        fr.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return;
}
代码语言:javascript
复制
Java7读取CSV文件:

public class ReadFileCsvUtils {

    private static final String fileNamePath = "/Users/Downloads/Data/faculty.csv";

    public static void main(String[] args) {
        readCsvFile(fileNamePath);
    }

    public static void readCsvFile(String fileNamePath) {
        try {
            // 换成你的文件名
            BufferedReader reader = new BufferedReader(new FileReader(fileNamePath));
            reader.readLine();//第一行信息,为标题信息,不用,如果需要,注释掉
            String line = null;
            while ((line = reader.readLine()) != null) {
                // CSV格式文件为逗号分隔符文件,这里根据逗号切分
                String[] item = line.split(",");
                System.out.println(new Gson().toJson(item));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Write文件

代码语言:javascript
复制
Java7写TXT文件:

// FileWriter的第二个参数代表是否追加
BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile, true));
// 字符串中使用换行:\r\n
writer.write(ss);
writer.newLine();
writer.close();
代码语言:javascript
复制
Java7写CSV文件:

public void writeCsvFile(String fileNamePath) {

    List<String> data = new ArrayList();
    try {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileNamePath, true));
        bufferedWriter.write("第一列, 第二列, 第三列, 第四列");
        for (int i = 0; i < data.size(); i++) {

            bufferedWriter.write(data.get(i));
            bufferedWriter.newLine();
        }
        bufferedWriter.flush();
        bufferedWriter.close();

    } catch (Exception e) {
        log.error("error:" + e.getMessage());
    }
}

Cut文件

代码语言:javascript
复制
public class CutFileUtils {

    /**
     * 按指定大小切割文件
     * @param args
     */
    public static void main(String[] args) {
        //调用cutFile()函数 传人参数分别为 (原大文件,切割后存放的小文件的路径,切割规定的内存大小)
        cutFile("/Users/Documents/projects/logs/searchmanager/Data/logs/service/SearchManager.2020-11-18-1.log",
                "/Users/Documents/projects/logs/searchmanager/", 1024 * 1024 * 1000);
    }


    /**
     * @param src    需要切割的文件
     * @param endsrc 切割后文件的存放路径
     * @param num    每个文件的大小
     */
    public static void cutFile(String src, String endsrc, int num) {
        FileInputStream fis = null;
        File file = null;
        try {
            fis = new FileInputStream(src);
            file = new File(src);
            //创建规定大小的byte数组
            byte[] b = new byte[num];
            int len = 0;
            //name为以后的小文件命名做准备
            int name = 1;
            //遍历将大文件读入byte数组中,当byte数组读满后写入对应的小文件中
            while ((len = fis.read(b)) != -1) {
                //分别找到原大文件的文件名和文件类型,为下面的小文件命名做准备
                String name2 = file.getName();
                int lastIndexOf = name2.lastIndexOf(".");
                String substring = name2.substring(0, lastIndexOf);
                String substring2 = name2.substring(lastIndexOf, name2.length());
                FileOutputStream fos = new FileOutputStream(endsrc + "/" + substring + "-" + name + substring2);
                //将byte数组写入对应的小文件中
                fos.write(b, 0, len);
                //结束资源 fos.close();
                name++;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    //结束资源
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Read文件
  • Write文件
  • Cut文件
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档