This question already has an answer here:
Why will Gson pretty-print to the console, but not the file?
(1 answer)
Closed 4 years ago.
I am having hard time in writing pretty print json string on file using Gson library. Code I am using is here:
Gson gs = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
JsonWriter jsonWriter = null;
try {
jsonWriter = new JsonWriter(new OutputStreamWriter(stream, "UTF-8"));
jsonWriter.beginArray();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
for (Feed feed : feeds) {
gs.toJson(feed, Feed.class, jsonWriter);
}
try {
jsonWriter.endArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
jsonWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Here stream is nothing but a file output stream. Even though I have enabled the pretty printing but still I am getting unformatted json string on file.
Any help is appreciated.
You can simply enable the pretty print by setting the indent.
jsonWriter.setIndent(" ");
Related
I am using below JSON format:
[{object1},{object2},{object3}...]
I am reading a JSON file object wise means one by one (object by object) and my below code working fine.
I want to read it in chunks(at a time 10 objects). I have tried a lot but I am not getting any solution (without using Spring Batch). Can anybody please help me how to read in chunks
#Component
public class PdpiRunner3 implements CommandLineRunner {
#Override
public void run(String... args) throws Exception {
try {
JsonReader jsonReader = new JsonReader(new InputStreamReader(new ClassPathResource("/json/trades2.json").getInputStream(),StandardCharsets.UTF_8));
Gson gson = new GsonBuilder().create();
jsonReader.beginArray();
while (jsonReader.hasNext()) { // next json array element
PDPIfiles json = gson.fromJson(jsonReader, PDPIfiles.class);
if (json != null) {
System.out.println(json);
}
}
jsonReader.endArray();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Is it possible to read json element In Chunk without spring Batch pleas help ?
I am trying to write simple JSON data into a file but seems my file is blank. It does not write anything. When I print output in java console then it shows me correct.
import org.json.simple.JSONObject;
JSONObject obj = new JSONObject();
obj.put("Phone Number:", "XXXXXXXXX");
obj.put("Fname:", "Mike");
obj.put("Lname:", "Miller");
obj.put("Street:", "101");
try {
FileWriter file = new FileWriter("D:\\file1.json");
file.write(obj.toJSONString());
}
catch (Exception e) {
e.printStackTrace();
}
I saw similar code on the internet and SO as well. I am following same but still not sure why it is not writing output into a file.
This is updated working version
public static void main(String...strings) throws IOException{
FileWriter file = new FileWriter("C:\\file1.json");
try {
JSONObject obj = new JSONObject();
obj.put("Phone Number:","XXXXXXXXX");
obj.put("Fname:","Mike");
obj.put("Lname:","Miller");
obj.put("Street:","101");
file.write(obj.toString());
}catch (Exception E)
{
System.out.println(E);
E.printStackTrace();
}finally{
file.close();
}
}
The OS may not write the data into hardware until you call flush:
public static void main(String[] args) throws Exception {
JSONObject obj = new JSONObject();
obj.put("Phone Number:","XXXXXXXXX");
obj.put("Fname:","Mike");
obj.put("Lname:","Miller");
obj.put("Street:","101");
FileWriter file = new FileWriter("D:\\file1.json");
try {
file.write(obj.toJSONString());
}catch (Exception E) {
E.printStackTrace();
} finally {
file.flush();
file.close();
}
}
Here you are not flushing the data into files. That's why data is not written into file. If you also want to keep the existing data into the file, try appending. Here is the updated code that will append new data to that existing file.
import org.json.simple.JSONObject;
JSONObject obj = new JSONObject();
obj.put("Phone Number:","XXXXXXXXX");
obj.put("Fname:","Mike");
obj.put("Lname:","Miller");
obj.put("Street:","101");
try {
FileWriter file = new FileWriter("D:\\file1.json", true); // true to append at the end of file.
file.write(obj.toJSONString());
file.flush()
}catch (Exception E)
{
E.printStackTrace();
}finally{
file.close();
}
}
When you are writing code by using any Files classes, I mean either you writing the content into file or reading from file, closing the stream is always best practice.
The code should be like this,
FileWriter file = new FileWriter("D:\\file1.json");
file.write(obj.toJSONString());
file.close();
This question already has answers here:
java.io.FileNotFoundException when creating FileInputStream
(2 answers)
Closed 6 years ago.
For my application I want to use a Map to act as a database. To save and load a map, I am writing/reading it to/from database.ser using this 2 methods:
private synchronized void saveDB() {
try {
fileOut = new FileOutputStream(db);
out = new ObjectOutputStream(fileOut);
out.writeObject(accounts);
fileOut.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
private void loadDB() {
try {
fileIn = new FileInputStream(db);
in = new ObjectInputStream(fileIn); // that is where error is produced if fileIn is empty
accounts = (Map<String, Client>) in.readObject();
in.close();
fileIn.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I want to load into Map when application starts, so I invoke method in constructor like this:
protected DriveatorImpl() {
accounts = new ConcurrentHashMap<String, Client>();
db = new File("C:/Users/eduar/git/Multy-Threaded-Bank-System/Bank-Services/database.ser");
// also, any suggestions how can I make path to a file more flexible in case I want to run Server side of an app on different machine?
if (!db.exists()) {
try {
db.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
loadDB(); // loads database when server start
}
I am aware of what causing an error, but I don't know what should I change in my design to avoid ObjectInputStream constructor receiving empty stream!
Any suggestions on what I can do differently?
Edit: I want to note that in fresh application run database.ser is empty since there was no entries made into Map yet.
Thank You!
First why the EOFExcpetion occur?
There are no contents in file or file is empty and you tried to read file.
You can avoid the EOFException for an empty file by checking file content length if it is less than or equal to zero means file is empty. another way to check if file is empty
Some code change and it worked for me.
#SuppressWarnings("unchecked")
private void loadDB() {
try {
if (db.length() <= 0) {
// if statement evaluates to true even if file doesn't exists
saveDB(); // save to a file an empty map
// if file doesn't exist, it creates a new one
// call loadDB inside constructor
}
FileInputStream fileIn = new FileInputStream(db);
ObjectInputStream in = new ObjectInputStream(fileIn); // that is where error is produced if fileIn is empty
in.readObject();
in.close();
fileIn.close();
System.out.println(accounts);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Get rid of the file.exists()/file.createNewFile() crap. All it is doing for you is masking the original FileNotFoundException problem, and turning into a thoroughly predictable EOFException because of trying to construct an ObjectInputStream around an empty stream. Handle the original problem. Don't just move it, or turn it into something else.
I am using the following method to read from the internal storage:
private void deserialize(ArrayList<Alias>arrayList) {
try {
FileInputStream fis = openFileInput(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
arrayList = (ArrayList<Alias>)ois.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
It reads the content of the file "filename" to the "arrayList".
The "serialize" method is as follows:
void serialize(ArrayList<Alias>arrayList) {
FileOutputStream fos;
try {
fos = openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arrayList);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The problem is that I whenever I run my program again, the "arrayList" is empty. So I guess I am opening the file in wrong input mode.
My aim is to first get the array from the file, then modify it within the app, and then write the modified array back to the file.
Can someone please help me with my problem?
Thanks!
Can you post your pice of your source code? I think the way which you used to parse file content get issue.
Read here:
Android ObjectInputStream docs
I read that the method readObject() read the next object...i this that you must iterate with something like this:
MediaLibrary obj = null;
while ((obj = (MediaLibrary)objIn.readObject()) != null) {
libraryFromDisk.add(obj);
}
This question already has answers here:
How to prevent InputStream.readObject() from throwing EOFException?
(3 answers)
Closed 9 years ago.
I can't seem to find a way to make readObject() transfer it's contents to an object variable. When I step through the Load function I get to "temp = (HashMap) ois.readObject();" Before this line is executed I am able to see the HashMap's data that I've written with oos in the expressions window of Eclipse so I know the data is there, however when this line executes I'm jumped to the IOException catch with an EOF. From what I've read this is expected, but I have not found a way to catch the EOF (loops with available() and readObjectInt() did not work). I'm running this on an Android emulator. Any suggestions would be appreciated.
public void Save(Pottylog data)
{
try
{
FileOutputStream fos = openFileOutput("Plog", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(data.get());
oos.close();
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
catch (java.io.IOException e)
{
e.printStackTrace();
}
}
public HashMap<String, Integer> Load()
{
HashMap<String, Integer> temp = null;
try
{
FileInputStream fis = openFileInput("Plog");
ObjectInputStream ois = new ObjectInputStream(fis);
temp = (HashMap<String, Integer>) ois.readObject();
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return temp;
}
EOFException means you have reached the end of the stream. I don't know what you think you're seeing in the debugger, but there is no object there in the stream to be read. catch(EOFException exc) does work; at this point you should close the stream and exit the reading loop. Don't misuse available() as an end of stream test: that's not what it's for.