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.
我猜您正在使用Java 7,它只有一个版本的Files.newBufferedReader方法,该方法将Charset作为第二个参数https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files .html#newBufferedReader(java.nio.file.Path,%20java.nio.charset.Charset)在Java 8中,您将找到所需的方法https://docs.oracle.com/javase/8/docs/api/ java / nio / file / Files.html#newBufferedReader-java.nio.file.Path-
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.