无法使用Java中的BufferedReader读取大文件

时间:2022-08-23 08:57:57

I am trying to read a file using BufferedReader, but when I tried to print, It is returning some weird characters.

我正在尝试使用BufferedReader读取文件,但是当我尝试打印时,它返回了一些奇怪的字符。

Code of reading file is:

阅读文件的代码是:

private static String readJsonFile(String fileName) throws IOException{
        BufferedReader br = null;
        try {
            StringBuilder sb = new StringBuilder();
            br = new BufferedReader(new FileReader(fileName));
            String line = br.readLine();
            while(line != null ){
                sb.append(line);
                System.out.println(line);
                line=br.readLine();
            }
            return sb.toString();
        } finally{
            br.close();
        }
    }

This function is being called as :

此函数被称为:

 String jsonString = null;
    try {
        jsonString = readJsonFile(fileName);
    } catch (IOException e) {
        e.printStackTrace();
    }

But when I tried to print this in console using System.out.println(jsonString);, It is returning some fancy pictures.

但是当我尝试使用System.out.println(jsonString);在控制台中打印它时,它正在返回一些精美的图片。

Note: It is Working file when file size is small.

注意:文件大小较小时,它是工作文件。

Is there any limit on size of file it can read ?

它可以读取的文件大小是否有限制?

1 个解决方案

#1


You're using the platform default encoding to read the file, which is probably encoded in UTF8. Check the actual encoding of the file, and specify the encoding:

您正在使用平台默认编码来读取文件,该文件可能以UTF8编码。检查文件的实际编码,并指定编码:

BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream("...", StandardCharsets.UTF_8));

Note that since you simply want to read everything from the file, you could simply use

请注意,由于您只想阅读文件中的所有内容,因此您只需使用即可

String json = new String(Files.readAllBytes(...), StandardCharsets.UTF_8);

#1


You're using the platform default encoding to read the file, which is probably encoded in UTF8. Check the actual encoding of the file, and specify the encoding:

您正在使用平台默认编码来读取文件,该文件可能以UTF8编码。检查文件的实际编码,并指定编码:

BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream("...", StandardCharsets.UTF_8));

Note that since you simply want to read everything from the file, you could simply use

请注意,由于您只想阅读文件中的所有内容,因此您只需使用即可

String json = new String(Files.readAllBytes(...), StandardCharsets.UTF_8);