Cannot Load Values From JSON File - java

So, I'm trying to load some values from a JSON file:
{
Float :
null
,
test :
"hello"
,
Int :
2
}
However, the method I have below isn't working at all and doesn't load the file contents. No errors are thrown other than NPEs when I try to use various methods that return values loaded from the file. Any idea what I'm doing wrong?
protected void load(String name, String path) throws FileAlreadyLoadedException{
if (get(name) == null){
final ThunderFile tf = new ThunderFile(name, path);
//files.add(tf);
try {
final JSONObject jobj = (JSONObject)new JSONParser().parse(new FileReader(path + File.separator + name + ".json"));
new Thread(){
public void run(){
Iterator<?> i = jobj.keySet().iterator();
while(i.hasNext()){
String key = (String) i.next();
Object value = jobj.get(key);
if (!key.equals("") && !value.equals("")){
tf.set(key, value);
}
}
files.add(tf);
System.out.println("[Thunderbolt 2] Loaded " + tf.getName() + ".json");
this.interrupt();
}
}.start();
} catch(IOException | ParseException e) {
e.printStackTrace();
}
}else{
throw new FileAlreadyLoadedException("The File " + name + ".json is already loaded!");
}
}
EDIT:
To clarify, no values are loaded, even if my file looked like this:
{"Double":2.0}

Your JSON contains Float: null so Object value = jobj.get(key); for key Float is null.
Therefore !value.equals("") throws NPE.

Related

Why isn't my method working for writing a file using a HashMap to txt file

I am not entirely sure why my method is not working. I am using a write a file method which basically uses a HashMap to write to an external text file. which is the below
public void writeAMap(HashMap<String, String> map, String filename)
{
if(map != null) {
try (FileWriter writer = new FileWriter(filename, true)) {
for(String key : map.keySet()) {
String value = map.get(key);
if(value == null) {
System.out.println("Warning: Null response for " +
key + " in writeAMap. Using a default.");
value = "I don't know what you mean?";
}
writer.write(key.trim());
writer.write('\n');
writer.write(value.trim());
writer.write('\n');
}
writer.close();
}
catch(IOException e) {
System.out.println("Problem writing file: " + filename +
" in writeAMap");
}
}
else {
System.out.println("Null map passed to writeAMap.");
}
}
I am then calling the above method, using the method below in a another class
public void mapWrite(HashMap<String, String>map)
{
help.writeAMap(map, "responses.txt");
}
Then I wrote the below method in order to call the above method in the main class,
if (input.contains("write")) {
HashMap<String, String> key = new HashMap<String, String>();
instruct.mapWrite(key);
}
This compiles fine and gives no errors, but it isn't actually writing to the external txt file. any help on figuring out why that is would be great.

java.lang.IllegalArgumentException: File Not found

I am trying to read an Ontology using Jena. I have a file Pizza.owl in the correct directory shown in the code, but I still get an error that the file is not found.
public static void ReadOntology(){
OntModel onto = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, null);
String inputFileName = "C:\\Users\\najib\\studies\\pizza.owl";
try {
Logger logger = Logger.getLogger(Operations.class);
PropertyConfigurator.configure("C://Users//najib//Downloads//apache-jena-2.12.0//jena-log4j.properties");
//create the reasoning model using the base
OntModel model = ModelFactory.createOntologyModel();
// use the FileManager to find the input file
InputStream in = FileManager.get().open(inputFileName);
if (in == null) {
throw new IllegalArgumentException("File: " + inputFileName + " not found");
}
model.read(in, "");
//to list classes
ExtendedIterator<OntClass> classes = model.listClasses();
while (classes.hasNext()) {
OntClass cls = (OntClass) classes.next();
System.out.println("Classes: " + cls.getLocalName());
for (ExtendedIterator<OntClass> i = cls.listSubClasses(true); i.hasNext();) {
OntClass c = (OntClass) i.next();
System.out.print(" " + c.getLocalName() + "\n");
} // end for
}
} catch (Exception e) {
System.out.println(e);
}
}
}
I get the following error: java.lang.IllegalArgumentException: File: C:\Users\najib\studies\pizza.owl not found
When I read the javadoc of FileManager, I see you have to prefix your file parameter with "file:"
So (without testing this answer) I suggest to try it with:
String inputFileName = "file:/C:/Users/najib/studies/pizza.owl";

Java Json - Reading a file, editing the files values, and then saving the new edits

so I have finally got reading multiple JSON objects and arrays working, with help from (can't post because of reputation...) But I have ran into a problem.. I can't seem to output the changes I've made (setting values of objects). I can only output the changes. Not set the changes in the file I read from, then output the file with the changes.
Also I am using this library (Please use it if you'd like to help): https://mega.co.nz/#!LIkQ1Lwa!Jz0S1zdgYHzcpxpd2spmXxhAxu564Wrp0dUChqnDARU
Here's my code. (It might be messy. But it works for this silly json java thing)
try {
BufferedReader in = new BufferedReader(new InputStreamReader(ModBox.class.getResourceAsStream("/info/lynxaa/modbox/res/tunables.json")));
String line;
String out = "";
while ((line = in.readLine()) != null) {
out += line;
}
in.close();
JsonObject object = JsonObject.readFrom(out);
JsonObject ssObj = object.get("tunables").asObject();
JsonObject sssObj = ssObj.get("MP_GLOBAL").asObject();
JsonArray array = null;
//Fields we want to modify
String[] arrayObjects = {
"CARMOD_SHOP_MULTIPLIER",
"CLOTHES_SHOP_MULTIPLIER",
"HAIRDO_SHOP_MULTIPLIER",
"TATTOO_SHOP_MULTIPLIER",
"WEAPONS_SHOP_MULTIPLIER",
"CARS_WEBSITE_MULTIPLIER",
"PLANES_WEBSITE_MULTIPLIER",
"HELIS_WEBSITE_MULTIPLIER",
"BOATS_WEBSITE_MULTIPLIER",
"BIKES_WEBSITE_MULTIPLIER",
"XP_MULTIPLIER",
"CASH_MULTIPLIER",
"MAX_CASH_GIFT_LIMIT",
"MAX_HEALTH_MULTIPLIER",
"MIN_HEALTH_MULTIPLIER",
"HEALTH_REGEN_RATE_MULTIPLIER",
"HEALTH_REGEN_MAX_MULTIPLIER",
"MAX_ARMOR_MULTIPLIER"
};
final String DIR_ = System.getProperty("user.home") + File.separator + "Desktop" + File.separator + "MODBOX" + File.separator;
File output = new File(DIR_ + "gta_v_modbox_json" + new Random().nextInt(999) + ".json");
output.getParentFile().mkdirs();
output.createNewFile();
if (output.exists()) {
textArea.append("Created MODBOX files: " + output.getAbsolutePath() + "\n");
}
for (String objects : arrayObjects) {
array = sssObj.get(objects).asArray();
}
if (array == null) {
textArea.append("Error! Json Array outputted null.");
return;
}
for (JsonValue value : array.values()) {
double mvalue = value.asObject().get("value").asDouble();
for (String objss : arrayObjects) {
textArea.append(objss + ":" + mvalue + "\n");
for (Component component : tabMain.getComponents()) {
if (component instanceof JTextField) {
JTextField field = ((JTextField) component);
if (field.getName() == objss) {
textArea.append("Found match for: " + field.getName());
textArea.append("Setting value of: " + field.getName() + " to: " + Double.parseDouble(field.getText()));
value.asObject().add(objss, Double.parseDouble(field.getText()));
FileWriter fw = new FileWriter(output.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
value.writeTo(bw);
bw.close();
break;
}
}
}
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
And each time I save a file, this gets outputted:
{
"value": 1,
"XP_MULTIPLIER": 100,
"CASH_MULTIPLIER": 50,
"MAX_HEALTH_MULTIPLIER": 10000,
"MIN_HEALTH_MULTIPLIER": 10000,
"HEALTH_REGEN_RATE_MULTIPLIER": 10,
"MAX_ARMOR_MULTIPLIER": 10000
}
Instead of editing the actual file I read from.
Found here:
https://mega.co.nz/#!GMUC3ZqT!JsvNEG5FEKTMsIhlDJdNjHyH7714qH199WmcTxdVO-E
If you are using maven (which I strongly recommend), you must put this in your pom.xml file:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.3.0</version>
</dependency>
This will add jackson as a dependency to your project and maven will handle downloading it and adding it to the build path.
In order to serialize an object to json you need to create an ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
then use its writeValue method which takes a File/OutputStream/Writer as first parameter and Object as second.
mapper.writeValue(myFile, myData);
To deserialize json back to an object, you use the readValue() method, which takes as parameters File/InputStream/Reader and Object type.
For exmaple:
MyClass data = mapper.readValue(myFile, MyClass.class);
If you want to deserialize a collection(in this example a List) you can use
CollectionType ct = mapper.getTypeFactory().constructCollectionType(List.class,MyClass.class);
List<MyClass> myList = mapper.readValue(myFile, ct);
To read a Map (HashMap):
MapType mapType = objectMapper.getTypeFactory().constructMapType(HashMap.class, KeyClass.class, ValueClass.class);
final Map<KeyClass, ValueClass> data = objectMapper.readValue(myFile, mapType);
Arrays:
Data[] data = objectMapper.readValue(myFile, Data[].class);
And to modify your data, you can use simple setters/getters and then save again.

InputStream is null

In a program I'm working on I have
String cwd;
String file_separator;
public ConfigLoader()
{
cwd = get_cwd();
file_separator = get_file_separator();
try
{
Properties c = new Properties();
InputStream in = this.getClass().getClassLoader().getResourceAsStream(cwd +
file_separator + "data" + file_separator + "configuration.properties");
c.load(in);
}
except (Exception e) { e.printStackTrace(); }
}
public String get_file_separator()
{
File f = new File("");
return f.separator;
}
public String get_cwd()
{
File cwd = new File("");
return cwd.getAbsolutePath();
}
For some reason, though, c.load(in); causes a NullPointerException. The exception comes from in == NULL being true. I can't figure out why because
System.out.println(cwd + file_separator + "data" + file_separator +
"configuration.properties");
prints
/users/labnet/st10/jjb127/workspace/Brewer-Client/data/configuration.properties
which is the location of the file I'm wanting to use.
Thoughts?
getResourceAsStream is meant to search for files on the classpath and not for accessing the local file system. You will have to use FileInputStream for this case.
InputStream in = new FileInputStream(cwd +
file_separator + "data" + file_separator + "configuration.properties");

Java writing to a text file not working properly

The Java application that I support is logging some details in a flat file. the problem I face some times is that, the entry is very low compared to the previous day. This entry is most essential because our reports are generated based on the file. I went thro code for writing I couldn't figure out any issues. the method which is writing is sync method.
Any suggestions? I can also provide the code for you is you may need?
public synchronized void log (String connID, String hotline, String callerType,
String cli, String lastMenu, String lastInput,
String status, String reason)
{
//String absoluteFP = LOG_LOC + ls + this.getFilename();
//PrintWriter pw = this.getPrintWriter(absoluteFP, true, true);
try
{
pw.print (this.getDateTime ()+ ","+connID +","+hotline+","+callerType+","+ cli+"," + lastMenu + "," + lastInput + "," + status + "," + reason);
//end 1006
pw.print (ls);
pw.flush ();
//pw.close();
}
catch (Exception e)
{
e.printStackTrace ();
return;
}
}
private synchronized PrintWriter getPrintWriter (String absoluteFileName,
boolean append, boolean autoFlush)
{
try
{
//set absolute filepath
File folder = new File (absoluteFileName).getParentFile ();//2009-01-23
File f = new File (absoluteFileName);
if (!folder.exists ())//2009-01-23
{
//System.out.println ("Call Detailed Record folder NOT FOUND! Creating a new);
folder.mkdirs ();
//System.out.println ("Configure log folder");
this.setHiddenFile (LOG_LOC);//set tmp directory to hidden folder
if (!f.exists ())
{
//System.out.println ("Creating a new Call Detailed Record...");//2009-01-23
f.createNewFile ();//2009-01-23
}
}
else
{
if (!f.exists ())
{
//System.out.println ("Creating a new Call Detailed Record...");//2009-01-23
f.createNewFile ();//2009-01-23
}
}
FileOutputStream tempFOS = new FileOutputStream (absoluteFileName, append);
if (tempFOS != null)
{
return new PrintWriter (tempFOS, autoFlush);
}
else
{
return null;
}
}
catch (Exception ex)
{
ex.printStackTrace ();
return null;
}
}
/**
* Set the given absolute file path as a hidden file.
* #param absoluteFile String
*/
private void setHiddenFile (String absoluteFile)
{
//set hidden file
//2009-01-22, KC
Runtime rt = Runtime.getRuntime ();
absoluteFile = absoluteFile.substring (0, absoluteFile.length () - 1);//2009-01-23
try
{
System.out.println (rt.exec ("attrib +H " + "\"" + absoluteFile + "\"").getInputStream ().toString ());
}
catch (IOException e)
{
e.printStackTrace ();
}
}
private String getDateTime ()
{
//2011-076-09, KC-format up to milliseconds to prevent duplicate PK in CDR table.
//return DateUtils.now ("yyyy/MM/dd HH:mm:ss");
return DateUtils.now ("yyyy/MM/dd HH:mm:ss:SSS");
//end 0609
}
private String getFilename ()
{
///return "CDR_" + port + ".dat";//2010-10-01
return port + ".dat";//2010-10-01
}
public void closePW ()
{
if (pw != null)
{
pw.close ();
}
}
You've created a FileOutputStream, but aren't closing that stream. Close that stream and try again. That might be causing the problem.
Messages are getting logged sometime because the garbage collector kicks in at some intervals and closes the FileOutStream. This then allows messages to be logged again. You're getting the unreachable error since you have a return statement in both the if & else blocks. You'll have to take the PrintWriter and FileOutStreamWriter out of the getPrintWriter put it where you usually call the getPrintWriter(). Then you'll be able to close the streams correctly. getPrintWriter should only ensure file exists, so rename it to ensureFileExistance
If you can use Apache Common IO, try this:
public synchronized void log(String connID, String hotline, String callerType,
String cli, String lastMenu, String lastInput,
String status, String reason) {
String absoluteFP = LOG_LOC + ls + this.getFilename();
File file = new File(absoluteFP);
String message = this.getDateTime() + "," + connID + "," + hotline + "," + callerType + "," + cli + "," + lastMenu + "," + lastInput + "," + status + "," + reason;
try {
// note that you must explicitly add new line character if you want the line to end with newline
FileUtils.write(file, message + "\n", "UTF-8", true);
} catch (IOException ex) {
ex.printStackTrace ();
}
}
In Common IO 2.1, you can append a file that you are writting to. You can now get rid of the closePW and getPrintwriter and since the log method is synchronized, the file can be written one at a time from the same object. However, if you try to write the same file from different object at the same time, you will end up having overwritting problem.
Also, Common IO create the missing parent folder for you automatically. There is no need to explicitly check and create the folder.

Categories

Resources