我尝试用Gson
进行配置,我做了这个代码的例子:
Channel c = new Channel(3, "TEST STRING!");
Gson gson = new GsonBuilder().create();
FileWriter writer = new FileWriter("config.json");
gson.toJson(c, writer);
writer.flush();
Reader reader = new InputStreamReader(Bot.class.getResourceAsStream("config.json"), "UTF - 8");
Gson ab = new GsonBuilder().create();
Channel a = ab.fromJson(reader, Channel.class);
System.out.println(a);
但我有错误:java.lang.NullPointerException
在线
Reader reader = new InputStreamReader(Bot.class.getResourceAsStream("config.json"), "UTF - 8");
我哪里搞错了?
另一个问题,如何在文件中进行配置?
选项一:您正在读取的文件不能在运行时创建,您可以在开发环境中手动创建它,就像创建java源文件一样。这样它就可以在类路径上,通过getResourceAsStream()
:提供给您
项目布局:
MyProject
└── src
└── config.json // option one
└── com
└── myproject
└── Main.java
└── config.json // option two
您的代码:
// If you placed config.json at location 1 (notice the leading slash)
Reader reader = new InputStreamReader(Bot.class.getResourceAsStream("/config.json"), "UTF - 8");
// If you placed config.json at location 2 (notice no leading slash)
Reader reader = new InputStreamReader(Bot.class.getResourceAsStream("config.json"), "UTF - 8");
Gson ab = new GsonBuilder().create();
Channel a = ab.fromJson(reader, Channel.class);
System.out.println(a);
选项二:这可能是你问题的解决方案,但我想我会澄清getResourceAsStream()
的作用。与其尝试在类路径上查找config.json
,不如从刚保存到的文件中再次加载它。
// You might need to add this import
import java.nio.charset.StandardCharsets;
/*
* THIS BLOCK SAVES THE `Channel` INSTANCE TO THE FILE `config.json`
*/
// I also fixed this. Always specify your encodings!
try(FileOutputStream fos = new FileOutputStream("config.json");
OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
BufferedWriter writer = new BufferedWriter(osw))
{
Channel c = new Channel(3, "TEST STRING!");
Gson gson = new GsonBuilder().create();
gson.toJson(c, writer);
} // This is a "try-with-resources" statement. The Closeable resource defined in the try() block will automatically be closed at the end of the try block.
/*
* THIS BLOCK RECONSTRUCTS THE JUST SAVED `Channel` instance from the file `config.json`
*/
// This opens the file 'config.json' in the working directory of the running program
try(FileInputStream fis = new FileInputStream("config.json");
InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(isr))
{
Gson ab = new GsonBuilder().create();
Channel a = ab.fromJson(reader, Channel.class);
System.out.println(a);
} // Again, a try-with-resources statement