Option one: The file you are reading cannot be created at runtime and you create it by hand in your development environment, just like you would create a java source file. That way it can be on the classpath, available to you via getResourceAsStream()
:
Project layout:
MyProject
└── src
└── config.json // option one
└── com
└── myproject
└── Main.java
└── config.json // option two
Your code:
// 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);
Option two: This is probably the solution to your question, but I figured I would clarify what getResourceAsStream()
does. Instead of trying to find config.json
on the classpath, load it again from the file you just saved it to.
// 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