从Java文件夹中读取一堆JSON文件



我试图在Java类中读取一堆JSON文件。我试过这个

InputStream is = Myclass.class.getResourceAsStream("/data");
InputStreamReader in = new InputStreamReader(is);
BufferedReader b = new BufferedReader(in);
Stream<String> lines = bufferedReader.lines();

我得到了一个Stream<String>,其中包含一堆JSON文件名的字符串。我得到了所有JSON名称字符串,但我如何访问每个JSON,比如将每个JSON传输到对象或其他操作

这是我的包结构

src
--MyClass.java
data
--One.json
--Two.json
--Three.json

如果我理解正确,您只想读取某个文件夹内的所有.json文件。

您可以使用java.nio包遍历所有文件并轻松实现相同的目标。
示例:

文件夹结构
src
--java files
data
--subfolder
--abc.txt 
--another.txt
--one.json
--two.json

遍历data文件夹,只获取.josn文件

String dir =System.getProperty("user.dir")+"/data";

try{
List<Path> paths = Files.walk(Paths.get(dir),1) //by mentioning max depth as 1 it will only traverse immediate level   
.filter(Files::isRegularFile) 
.filter(path-> path.getFileName().toString().endsWith(".json")) // fetch only the files which are ending with .JSON
.collect(Collectors.toList());
//iterate all the paths and fetch data from corresnponding file                                 
for(Path path : paths) {
//read the Json File . change here according to your logic
String json = new String(Files.readAllBytes(path));
}           
}catch (Exception e) {
e.printStackTrace();
}  

需要读取单个文件,而不是像'tgdavies'建议的那样读取目录。

Path dir = Paths.get("data");

try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.json")) {
for (Path p : stream) {

BufferedReader buffReader = Files.newBufferedReader(p);

// rest of reading code ...
}
}

或者使用java.nio.file.Files读取所有行

Path dir = Paths.get("data");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.json")) {
for (Path p : stream) {

Stream<String> lines = Files.lines(p);
String data = lines.collect(Collectors.joining(System.lineSeparator()));

// rest of code logic ...
lines.close();
}
}

最新更新