I have list of json files as below:
At the moment, T.json file is empty. All the other files already have some text. What I need is to create something like this:
1.At the beginning of the T.json file add sth like
{
"T": [
2.Copy text from e.g. T_Average.json and T_Easy.json to T.json file
3.At the end of T.json file add this:
]
}
So at the end of program execution I need to have in my T.json sth like:
{
"T": [
text from T_Average.json
text from T_Easy.json
]
}
So how can I add text from 1st and 3rd step to the file?
And how can I copy everything from other files to T.json file?
I have already tried some solutions like this:
try(FileWriter fw = new FileWriter("T.json", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println("the text");
out.println("more text");
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
or like this one:
try {
String data = " This is new content";
File file = new File(FILENAME);
if (!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
bw.write(data);
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
but all the time, after line with fw = new FileWriter() it was jumping right to the catch clause.
So one more time:
How can I add text from 1st and 3rd step to the file?
And how can I copy everything from other files to T.json file?
Thanks :)
Try
1. Add following methods getJsonFromAssetFile and writeFile to your code
2. Read json file
String content = getJsonFromAssetFile("T_Difficult.json");
3 Create final json (as mentioned)
JSONObject finalJson = new JSONObject();
try {
JSONObject jsonObject = new JSONObject(content);
JSONArray jsonArray = new JSONArray();
jsonArray.put(jsonObject);
finalJson.put("T", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
4. Write final json to file
writeFile(finalJson.toString().getBytes());
writeFile
public static void writeFile(byte[] data, File file) throws IOException {
BufferedOutputStream bos = null;
try {
FileOutputStream fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(data);
}
finally {
if (bos != null) {
try {
bos.flush ();
bos.close ();
}
catch (Exception e) {
}
}
}
}
getJsonFromAssetFile
public static String getJsonFromAssetFile(Context context, String jsonFileName) {
String json = null;
try {
InputStream is = context.getAssets().open(jsonFileName);
int size = is.available ();
byte[] buffer = new byte[size];
is.read (buffer);
is.close ();
json = new String(buffer, "UTF-8");
}
catch(IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
NOTE: Read json asset file using getJsonFromAssetFile method and Write file on internal/external storage and provide proper path to writeFile method
Related
I've taken input from editText and trying to write its text to a json file. When I execute the code, it works without any errors. But when I try to read the json file again it doesn't have the previously written objects.
I've tried using different writers like BufferedWriter, FileWriter. None of them works.
This is the writeToJsonFile method
void writeJsonFile(TextView textView) {
String json;
try {
InputStream is = context.getAssets().open("chores.json");
int size = is.available();
byte[] buffer = new byte[size];
if (is.read(buffer) == -1) {
throw new EOFException();
}
is.close();
json = new String(buffer, StandardCharsets.UTF_8);
JSONObject obj = new JSONObject(json);
JSONObject m_jArray = obj.getJSONObject("chores");
JSONArray jsonArray = m_jArray.getJSONArray(title);
JSONObject new_jobj = new JSONObject();
new_jobj.put("task", textView.getText());
new_jobj.put("isCompleted", false);
jsonArray.put(new_jobj);
File file = new File(context.getExternalFilesDir("/assets"), "chores.json");
writeJsonFile(file, obj);
Log.i("Done => ", "Written to file");
} catch (EOFException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
This function takes a file and a json object and writes the json object to the file
public static void writeJsonFile(File file, JSONObject json) throws IOException {
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(json.toString());
if (fileWriter != null) {
fileWriter.close();
}
}
I expect it to write the json string to the file, but next time I read the file again with the InputStream, It doesn't show the previously added Object.
expected chores.json
{
"chores": {
"Daily": [
{
"task": "Task 1",
"isCompleted": false
}
],
"Weekly": [
],
"Monthly": [
],
"Custom": [
]
}
}
resulting json
{
"chores": {
"Daily": [
],
"Weekly": [
],
"Monthly": [
],
"Custom": [
]
}
}
You are not writing newly created object into file: For example:
...
JSONObject new_jobj = new JSONObject();
new_jobj.put("task", textView.getText());
new_jobj.put("isCompleted", false);
jsonArray.put(new_jobj);
File file = new File(context.getExternalFilesDir("/assets"), "chores.json");
// here instead of old obj write newly created new_jobj to file.
writeJsonFile(file, new_jobj);
Log.i("Done => ", "Written to file");
...
Before that make sure you have read and write storage permisions....
Ex.
try
{
Writer output = null;
File file = new File("filePath");
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
output = new BufferedWriter(new FileWriter(file));
output.write(jsonObject.toString());
output.close();
} catch (Exception e) {
e.printStackTrace();
}
You can use the append property in FileWriter constructor. You can try it.
FileWriter fileWriter = new FileWriter(file,true);
create and download zip file by adding list of text files. with out creating the file in local server, it should be download at client side direct,
Here i added a code snippet, it was creating in local server, but i dont want that, it should create and download at client side instant. Please help me in this way..
#GetMapping("/download/rawdata")
public void downloadRawdata(#RequestParam("date") String date){
log.info("date : "+date);
List<Rawdata> rawdatas = rawdataRepoisotry.findRawdataByDate(date);
log.info("size of rawdata : "+rawdatas.size());
List<File> files = new ArrayList<File>();
int i = 1;
for(Rawdata rawdata : rawdatas){
log.info("rawdata : "+ rawdata.getRawdata());
File file = new File(i+".txt");
try (Writer writer = new BufferedWriter(new FileWriter(file))) {
String contents = rawdata.getRawdata();
writer.write(contents);
files.add(file);
} catch (IOException e) {
e.printStackTrace();
}
i++;
}
try {
zipFile(files, new File(date+".zip"));
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("Failed while creating Zip file");
}
}
public FileOutputStream zipFile(final List<File> files, final File targetZipFile) throws IOException {
try {
FileOutputStream fos = new FileOutputStream(targetZipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
byte[] buffer = new byte[128];
for(File currentFile : files){
if (!currentFile.isDirectory()) {
ZipEntry entry = new ZipEntry(currentFile.getName());
FileInputStream fis = new FileInputStream(currentFile);
zos.putNextEntry(entry);
int read = 0;
while ((read = fis.read(buffer)) != -1) {
zos.write(buffer, 0, read);
}
zos.closeEntry();
fis.close();
}
}
zos.close();
fos.close();
return fos;
} catch (FileNotFoundException e) {
System.out.println("File not found : " + e);
throw new FileNotFoundException();
}
}
Here is an example using FileSystemResource.
What has been modified is (see the numbers in the commented code ) :
1) Declare that the response will be of type application/octet-stream
2) #ResponseBody
Annotation that indicates a method return value should be bound to the
web response body
3) Declare that the method returns a FileSystemResource body
4) Return the FileSystemResource entity based on your created zip file
Note that this will still create the file on the server side first, but you may want to use File.createTempFile and File.deleteOnExit.
#GetMapping("/download/rawdata", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)//1
#ResponseBody //2
public ResponseEntity<FileSystemResource> downloadRawdata(#RequestParam("date") String date){ //3
log.info("date : "+date);
List<Rawdata> rawdatas = rawdataRepoisotry.findRawdataByDate(date);
log.info("size of rawdata : "+rawdatas.size());
List<File> files = new ArrayList<File>();
int i = 1;
for(Rawdata rawdata : rawdatas){
log.info("rawdata : "+ rawdata.getRawdata());
File file = new File(i+".txt");
try (Writer writer = new BufferedWriter(new FileWriter(file))) {
String contents = rawdata.getRawdata();
writer.write(contents);
files.add(file);
} catch (IOException e) {
e.printStackTrace();
}
i++;
}
try {
File resultFile = new File(date+".zip");
zipFile(files, resultFile);
return new ResponseEntity<>(new FileSystemResource(resultFile), HttpStatus.OK); //4
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("Failed while creating Zip file");
}
}
every time the code runs i want the new record to be added to a new line
as it is when a new record is added it will write over previous line
private void writeFile() {
String FILENAME = g.getText();
String content = results;
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, MODE_PRIVATE);
fos.write(content.getBytes());
Toast.makeText(getApplicationContext(), "File Saved", 0).show();
} catch (IOException e) {
e.printStackTrace();
}
}
You need to write the "newline" character as well when writing data:
private void writeFile() {
String FILENAME = g.getText();
String content = results;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(content.getBytes());
fos.write(System.getProperty("line.separator"));
} catch (IOException e) {
e.printStackTrace();
}
}
But be careful with writing binary data like this. It's better to use e. g. BufferedWriter to write string data:
BufferedWriter writer = new BufferedWriter(new FileWriter("filename"));
writer.write("Hello world!");
writer.newLine();
private void saveFormActionPerformed(java.awt.event.ActionEvent evt) {
name = nameFormText.getText();
surname = surnameFormText.getText();
age = Integer.parseInt(ageFormText.getText());
stadium = stadiumFormText.getText();
Venues fix = new Venues();
fix.setName(name);
fix.setSurname(surname);
fix.setAge(age);
fix.setStadium(stadium);
File outFile;
FileOutputStream fStream;
ObjectOutputStream oStream;
try {
outFile = new File("output.data");
fStream = new FileOutputStream(outFile);
oStream = new ObjectOutputStream(fStream);
oStream.writeObject(fix);
JOptionPane.showMessageDialog(null, "File written successfully");
oStream.close();
} catch (IOException e) {
System.out.println(e);
}
}
This is what I have so far. Any ideas on what I could do with it to append the file if it's already created?
You have first to check if the file exists before, if not create a new one. To learn how to append object to objectstream take a look at this question.
File outFile = new File("output.data");
FileOutputStream fStream;
ObjectOutputStream oStream;
try {
if(!outFile.exists()) outFile.createNewFile();
fStream = new FileOutputStream(outFile);
oStream = new ObjectOutputStream(fStream);
oStream.writeObject(fix);
JOptionPane.showMessageDialog(null, "File written successfully");
oStream.close();
} catch (IOException e) {
System.out.println(e);
}
Using Java 7, it is simple:
final Path path = Paths.get("output.data");
try (
final OutputStream out = Files.newOutputStream(path, StandardOpenOption.CREATE,
StandardOpenOption.APPEND);
final ObjectOutputStream objOut = new ObjectOutputStream(out);
) {
// work here
} catch (IOException e) {
// handle exception here
}
Drop File!
Here is the code:
Thread clientThread = new Thread() {
#Override
public void run() {
try {
client = new Client();
quest = client.readFile();
Log.v("Client string", quest);
//File file = new File(myContext.getFilesDir(), "questionnaire.xml");
//BufferedWriter bw = new BufferedWriter(new FileWriter(file));
//bw.write(quest);
File tempFile = File.createTempFile("questionnaire", ".xml");
FileOutputStream fout = new FileOutputStream(tempFile);
PrintStream out = new PrintStream(fout);
out.println(quest);//InputStream stream = new ByteArrayInputStream(quest.getBytes("UTF-8"));
//getResources().op
try {
Serializer serializer = new Persister();
responseToQuestionnaire = serializer.read(ResponseToQuestionnaire.class, tempFile);
}
catch(Exception e) {}
Log.v("Let's seeeeee",responseToQuestionnaire.getQuestionnaireTemplate().toString());
} catch (Exception e1) {
e1.printStackTrace();
}
// try {
// OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
// openFileOutput(currentQuestionnaire.getName(),
// Context.MODE_PRIVATE));
// outputStreamWriter.write(client.readFile());
// outputStreamWriter.close();
// } catch (IOException e) {
// Log.e("Exception", "File write failed: " + e.toString());
// }
}
};
clientThread.start();
The code throws a Null Pointer exception even when quest is a full length string that prints in log perfectly fine. I tried multiple ways of saving the file but SimpleXML doesn't serialize string... only XML files.
Buffered streams don't necessarily write the data until they have to. Try closing the output stream before you call the read() method.