一段读取文件转换成字符串的代码,请问如何优化,并且根据文件夹中文件的数量读取文件

问题一

我想优化下面这段代码

问题二

我在读取文件之前,先获取文件夹中文件的数量,然后根据文件的数量遍历文件,将文件转换成字符串

// 文件解析成字符串

        ClassLoader classLoader = TelecomThreeListener.class.getClassLoader();

        URL resource = classLoader.getResource("bauschData/selectData01.json");
        String path = resource.getPath();
        //System.out.println(path);
        String fileName01 = path;

        resource = classLoader.getResource("bauschData/selectData02.json");
        path = resource.getPath();
        String fileName02 = path;

        resource = classLoader.getResource("bauschData/selectData03.json");
        path = resource.getPath();
        String fileName03 = path;

        // 默认读取文件

        File file = new File(fileName01);
        StringBuffer sb = new StringBuffer();
        String line;
        BufferedReader br=null;

        // 数据 - 无

        try {
            br=new BufferedReader(new FileReader(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            while((line=br.readLine())!=null){
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        String nothing = sb.toString();


        // 数据 - 1

        file = new File(fileName01);
        sb = new StringBuffer();
        try {
            br=new BufferedReader(new FileReader(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            while((line=br.readLine())!=null){
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        String bauschDataJson01 = sb.toString();

        // 数据 - 2

        file = new File(fileName02);
        sb = new StringBuffer();
        try {
            br=new BufferedReader(new FileReader(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            while((line=br.readLine())!=null){
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        String bauschDataJson02 = sb.toString();


        // 数据 - 3

        file = new File(fileName03);
        sb = new StringBuffer();
        try {
            br=new BufferedReader(new FileReader(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            while((line=br.readLine())!=null){
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        String bauschDataJson03 = sb.toString();
阅读 2.6k
3 个回答
File root  = new File(App.class.getClassLoader().getResource("bauschData/").getPath());
Arrays
    .stream(Objects.requireNonNull(root.listFiles( )))
    .filter(file -> file.getName().endsWith("json"))
    .map(File::toPath)
    .forEach(path -> {
        try {
            List<String> lines = Files.readAllLines(path);
        } catch (IOException e) {
            e.printStackTrace( );
        }
});

你要算一下所有文件的大小你内存放得下不,如果放不下那最好改成 Scanner 逐行扫描的方式去读。

问题一:
从文件中读取数据的代码可以封装为一个单独的方法,例如:

public static String readFileAsString(String filePath) throws IOException {
    return readFileAsString(new File(filePath));
}

public static String readFileAsString(File file) throws IOException {
    try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
        StringBuilder content = new StringBuilder();

        for (String line; (line = reader.readLine()) != null;) {
            content.append(line);
        }

        return content.toString();
    }
}

如果使用 Java8,readFileAsString 方法会更简单:

public static String readFileAsString(File file) throws IOException {
    return Files.lines(file.toPath()).collect(Collectors.joining(""));
}

这样的话,你就不需要每次读取某个文件的时候,都写一堆逻辑同样的代码,而是直接调用 readFileAsString 方法就行。

问题二:
Java 遍历某个目录的 API 很多,如果只是非递归遍历,即只列出当前目录的文件,可以使用:

  1. File 类的 listFiles 方法
  2. Files 类的 list 方法,返回 Stream<Path>,从而可以使用 Lambda 表达式。
File root  = new File(App.class.getClassLoader().getResource("bauschData/").getPath());
Arrays
    .stream(Objects.requireNonNull(root.listFiles( )))
    .filter(file -> file.getName().endsWith("json"))
    .map(File::toPath)
    .forEach(path -> {
        try {
            List<String> lines = Files.readAllLines(path);
        } catch (IOException e) {
            e.printStackTrace( );
        }
});

你要算一下所有文件的大小你内存放得下不,如果放不下那最好改成 Scanner 逐行扫描的方式去读。

—————————————————————————————————
—————————————————————————————————
—————————————————————————————————

问题一:
从文件中读取数据的代码可以封装为一个单独的方法,例如:

public static String readFileAsString(String filePath) throws IOException {
    return readFileAsString(new File(filePath));
}

public static String readFileAsString(File file) throws IOException {
    try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
        StringBuilder content = new StringBuilder();

        for (String line; (line = reader.readLine()) != null;) {
            content.append(line);
        }

        return content.toString();
    }
}

如果使用 Java,readFileAsString 方法会更简单:

public static String readFileAsString(File file) throws IOException {
    return Files.lines(file.toPath()).collect(Collectors.joining(""));
}

这样的话,你就不需要每次读取某个文件的时候,都写一堆逻辑同样的代码,而是直接调用 readFileAsString 方法就行。

问题二:
Java 遍历某个目录的 API 很多,如果只是非递归遍历,即只列出当前目录的文件,可以使用:

  1. File 类的 listFiles 方法
  2. Files 类的 list 方法,返回 Stream<Path>,从而可以使用 Lambda 表达式。
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题