简体   繁体   中英

new BufferedReader in class Files cannot be applied to given types

在此处输入图片说明

List< String> list = new ArrayList<>();

try (BufferedReader br = Files.newBufferedReader(Paths.get(path))) {

    //br returns as stream and convert it into a List
    list = br.lines().collect(Collectors.toList());

} catch (IOException e) {
     e.printStackTrace();
}

StringBuilder sb = new StringBuilder();
for (String s : list) {
    sb.append(s);
}

String json = sb.toString();
JSONParser parser = new JSONParser();
obj = parser.parse(json);

I am getting this error please help !!

The Files#newBufferedReader method takes a mandatory second parameter which is a character set. If you try the following code, the error should go away:

List< String> list = new ArrayList<>();

Charset charset = Charset.forName("US-ASCII");

try (BufferedReader br = Files.newBufferedReader(Paths.get(path), charset)) {
    list = br.lines().collect(Collectors.toList());
} catch (IOException e) {
    e.printStackTrace();
}

This assumes that your file is encoded in US-ASCII , though if you had another encoding, you could specify that as well. For example, if your file were UTF-8 encoded, you could use:

Charset charset = StandardCharsets.UTF_8;  

Edit:

After the seeing the accepted answer, I noticed that Java 8 introduced a one argument version of Files#newBufferedReader which just takes a single path as input. However, this is really a helper method which just calls the following:

return newBufferedReader(path, StandardCharsets.UTF_8);

In other words, it defaults to using UTF-8 encoding. If you want to use some other encoding, then my answer is probably the best approach for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM