如今我正在学习Maven。我从应用程序的resources文件夹中读取json文件时遇到问题。我收到一条错误消息“系统找不到此文件”。更有趣的是,当我尝试读取txt文件时没有问题...
您可以在下面的图片中看到,这两个文件在我的应用程序中位于同一位置。为什么我的json文件无法正确读取?
//WORKING
String filename = "./resources/data/init_data.txt";
try (Stream<String> lines = Files.lines(Paths.get(filename))){
lines.forEach(System.out::println);
} catch (Exception e){
e.printStackTrace();
}
//NOT WORKING
Gson gson = new Gson();
filename = "./resources/data/car.json";
try (Reader reader = new FileReader(filename)){
Car car3 = gson.fromJson(reader,Car.class);
System.out.println(car3);
} catch (IOException e){
e.printStackTrace();
}
答案 0 :(得分:0)
您可以使用addDays
来读取资源文件。
示例:
LocalDate
这假设getResourceAsStream()
是
import java.io.Reader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.google.gson.Gson;
...
public void getJson() {
try (Reader reader = new InputStreamReader(this.getClass()
.getResourceAsStream("/foo.json"))) {
MyResult result = new Gson().fromJson(reader, MyResult.class);
System.out.println(result.getBar()); // prints "bat"
} catch (IOException e) {
e.printStackTrace();
}
}
和foo.json
是:
{"bar": "bat"}
答案 1 :(得分:0)
fun getStringFromJsonFile(context: Context, fileId: Int): String {
val inputStream: InputStream = context.resources.openRawResource(fileId)
val writer: Writer = StringWriter()
val buffer = CharArray(1024)
try {
val reader: Reader = BufferedReader(InputStreamReader(inputStream, "UTF-8"))
var n = 0
while (reader.read(buffer).also { n = it } != -1) {
writer.write(buffer, 0, n)
}
return writer.toString()
} catch (error: Exception) {
Log.d(AppData.TAG, "Error : ${error.printStackTrace()}")
} finally {
inputStream.close()
}
return ""
}
//call method
val paymentJsonArr = JSONArray(getStringFromJsonFile(context, R.raw.payment_type))
//use data
for (i in 0 until paymentJsonArr.length()) {
val jsonObject = paymentJsonArr.getJSONObject(i)
}