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();
Related
Im currently building a GSONFileWriter class.
public class GSONFileWriter {
private File jsonFile;
private final String json;
public GSONFileWriter(String json) {
this.json = json;
}
public void generateJsonFileIfNotExists(String pathname) {
try {
jsonFile = new File(pathname);
if (!jsonFile.exists()) {
if (jsonFile.createNewFile()) {
System.out.println("File successful created.");
} else {
System.out.println("Error: Building the file went wrong!");
System.exit(1);
}
}
fillJsonFile();
} catch (Exception e) {
System.err.println("Error: Building the file went wrong!");
}
}
private void fillJsonFile() {
try (PrintWriter writer = new PrintWriter(jsonFile, StandardCharsets.UTF_8)) {
writer.append(json);
writer.println();
} catch (Exception e) {
e.printStackTrace();
}
}
}
it is called inside my CLI class
Gson gson = new Gson();
String json = gson.toJson(target);
GSONFileWriter gsonFileWriter = new GSONFileWriter(json);
gsonFileWriter.generateJsonFileIfNotExists("EmployeeData.json");
It creates and builds a new JSON File with an object inside it.
{"salary":34000.0,"name":"Hans","age":30,"id":"d40507a7-a802-4494-9a0c-5a97a0a4d0bf"}
However the Problem is, that whenever i run the code again, the old file gets overwritten and a new one created. I tried to change the code, so that it adds a new object to the file, instead of overwrite it. Any tips?
I would recommend:
At first: Read your json file as String if it exists.
String file = "<File>";
String json = new String(Files.readAllBytes(Paths.get(file)));
Second you transform this string into a JsonObject using JsonParser:
JsonObject object = JsonParser.parseString(json).getAsJsonObject();
now you obtained your json-file as JsonObject tree and can manipulate this as you like. Using:
JsonObject.get(<MemberName>);
JsonObject.add(String <propertyName>, JsonElement <value>);
JsonObject.addProperty(String <propertyName>, Number/String/Boolean/Char <value>);
, etc.
Whenever you are finished you can write this to your json-file, either through a OutputStream or whatever you like.
I want to read from a file and store it in a string.
This is my method:
public static String createJsonFileFromNode(String filename, JsonNode root) {
String dirName = "src/test/resources/json/";
File dir = new File (dirName);
File actualFile = new File (dir, filename);
try (Writer writer = new BufferedWriter(new OutputStreamWriter (
new FileOutputStream(actualFile), "utf-8")))
{
writer.write(String.valueOf(root));
log.info(actualFile.getPath());
String updatedJson = FileUtils.readFileToString(actualFile, "UTF-8");
return updatedJson;
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "";
} catch (FileNotFoundException e) {
e.printStackTrace();
return "";
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
I have two problems in the above method:
In String dirName = "src/test/resources/json/" I am passing an entire path, which I dont want to. I want to pass it as "/json/"
updatedJson is retuning null even though the file is getting saved to the particular direction. Not sure what is going on. Can someone please help me?
Thank you.
public void readList () {
try {
FileOutputStream writeData = new FileOutputStream("Accounts.txt");
ObjectOutputStream writeStream = new ObjectOutputStream(writeData);
writeStream.writeObject(AccountCredentials);
writeStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public void writeList() {
try {
FileInputStream readData = new FileInputStream("Accounts.txt");
ObjectInputStream readStream = new ObjectInputStream(readData);
AccountCredentials = (ArrayList <Accounts>) readStream.readObject();
readStream.close();
System.out.println(AccountCredentials.size());
}
catch (Exception e) {
e.printStackTrace();
}
}
My readList method works fine right, I have ¬í sr java.util.ArrayListxÒ™Ça I sizexp w
in the file. My writeList does not. I have a School folder inside the Netbeans folder, and in the main directory is Accounts.txt. Do I need to specify that? My Java file is in Schools/src. It always says my list size is 0
Can you please share the exception or stack trace you are getting and paste it here ? , Also I would highly recommend not to use a flat file for storing the account credentials, rather use any of the identity management solution and db driven account management. Did you also try to debug the following line "ObjectInputStream readStream = new ObjectInputStream(readData);"
I have the below 2 methods, supposed to read and write to a file:
/* Write content to a file */
private void writeToFile(ArrayList<String> list) {
#SuppressWarnings("unused")
File file = new File("jokesBody1.bjk");
FileOutputStream fos;
if(list != null){
try {
fos = openFileOutput("jokesBody1.bjk",Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(list);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
fos = openFileOutput("jokesBody1.bjk",Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject("");
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/* Read file's content */
private ArrayList<String> readFromFile() {
File file = new File("jokesBody1.bjk");
ArrayList<String> list = new ArrayList<String>();
try {
ObjectInputStream ois = new ObjectInputStream( new FileInputStream( file ) );
try {
list = (ArrayList)ois.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
ois.close();
} catch (IOException e) {
Log.e("log activity", "Can not read file: " + e.toString());
}
return list;
}
When I'm calling the above methods I'm getting this error:
02-15 10:28:48.165: E/log activity(1743): Can not read file: java.io.FileNotFoundException: /jokesBody1.bjk: open failed: ENOENT (No such file or directory)
Ok, it clearly says that the file is not there, but, isn't this code supposed to create it:
File file = new File("jokesBody1.bjk");
Why I'm getting this error? I know that I'm missing something small - probably a piece of code that creates the file(I'm not sure), but as a beginner, I'm not able to spot the issue.
File file = new File("jokesBody1.bjk");
Just creates a File objects that points to that path, but no actual file.
Use
file.createNewFile();
To actually create the file.
Ok, it clearly says that the file is not there, but, isn't this code supposed to create it:
Actually, no. It only creates a File object, an then java assumes that file to exist.
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);
}