I have a .json file that i am using like a property file. After reading the json file, i get the value from "Execute" node and then I want to update the "Execute" node with a value of "N".
My json file looks like this. {"RunDate":"2015-01-12","Execute":"Y"}. I wrote the code to read the json file and i am trying to update the file by writing a new file.
JSONParser parser = new JSONParser();
try {
FileReader fr = new FileReader("c:\\B\\myControl.json");
Object obj = parser.parse(fr);
JSONObject jsonObject = (JSONObject) obj;
ExecuteRun = (String) jsonObject.get("Execute");
RunDate = (String) jsonObject.get("RunDate");
//update
jsonObject.put("Execute", "N");
jsonObject.put("RunDate", RunDate);
FileWriter file = new FileWriter("c:\\B\\mycontrol.json", true);
try {
file.write(jsonObject.toJSONString());
} catch (Exception e) {
e.printStackTrace();
} finally {
file.flush();
file.close();
}
} catch(Exception e) {
e.printStackTrace();
}
The FileWriter line gets "access denied" error.
Can anyone help me out?
//this worked for me
package com.FLP.utils;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.FileWriter;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
#SuppressWarnings("unchecked")
public class TestDataReader {
public static void main(String[] args) {
try (Reader reader = new FileReader(".\\testdata\\TC_11.json")) {
// Read JSON file
JSONParser parser = new JSONParser();
JSONObject data = (JSONObject) parser.parse(reader);
data.put(key value);
#SuppressWarnings("resource")
FileWriter file = new FileWriter(".\\testdata\\TC_11.json");
file.write(data.toJSONString());
file.flush();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
place this code
try (FileWriter file = new FileWriter("/C:/Users/itaas/Desktop/text1.txt")) {
file.write(js.toString());
System.out.println("Successfully Copied JSON Object to File...");
System.out.println("\nJSON Object: " + js);
}
} catch (Exception e) {
e.printStackTrace();
}
Related
I'm trying to read a json file from my local machine.
#Path("/")
public class JsonParsing {
File f = new File("file.json");
if (f.exists()){
InputStream is = new FileInputStream("file.json");
String jsonTxt = IOUtils.toString(is);
System.out.println(jsonTxt);
JSONObject json = new JSONObject(jsonTxt);
String a = json.getString("1000");
System.out.println(a);
}
}
But I'm getting error in toString() method.
Also is it possible to read a .txt file containing json object from my local machine? If possible, how it is done?
you may be using IOUtils and import sun.misc.IOUtils but the default does not include the method toString with parameter (InputStream) so you need to use apache common io lib to use this method and
import org.apache.commons.io.IOUtils;
Firstly: whenever you ask the question- add imports as well.
Secondly: yes it is possible to read a .txt file containing json object.
Steps:
1. Add Maven dependency in your pom.xml -
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
Or add the jar of this dependency.
2.imports in java file -
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
3. Sample Java code to read .txt file containing
this json object
{
"Name": "crunchify.com",
"Author": "App Shah",
"Company List": [
"Compnay: eBay",
"Compnay: Paypal",
"Compnay: Google"
]
}
#SuppressWarnings("unchecked")
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader(
"/Users/<username>/Documents/file1.txt"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("Name");
String author = (String) jsonObject.get("Author");
JSONArray companyList = (JSONArray) jsonObject.get("Company List");
System.out.println("Name: " + name);
System.out.println("Author: " + author);
System.out.println("\nCompany List:");
Iterator<String> iterator = companyList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (Exception e) {
e.printStackTrace();
}
}
Hope it helps.
Try:
File f = new File("file.json"); //it can be the same file "file.txt"
InputStream is = null;
if (f.exists()){
try {
is = new FileInputStream("file.json");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader r = new BufferedReader( new InputStreamReader( is ) );
StringBuilder stringBuilder = new StringBuilder();
String line;
String jsString = null;
try {
while (( line = r.readLine() ) != null) {
stringBuilder.append( line );
}
jsString = stringBuilder.toString();
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println(jsString);
JSONObject jsonObj = new JSONObject(jsString);
String a = jsonObj.getString("1000");
System.out.println(a);
}
Refer to:
Creating JSONObject from text file
I want to read the DNA text file of bacteria using java i made this
code
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
// implements a simplified version of "type" command provided in Windows given
// a text file name(s) as argument, it prints the content of the text file(s) on console
class Type {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\Users\\mohamed\\Downloads\\dataset_2_6.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
but the output is null
, it work when using small text file
I need to copy file from one place to another. I have found good solution :
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileCopyTest {
public static void main(String[] args) {
Path source = Paths.get("/Users/apple/Desktop/test.rtf");
Path destination = Paths.get("/Users/apple/Desktop/copied.rtf");
try {
Files.copy(source, destination);
} catch (IOException e) {
e.printStackTrace();
}
}
}
This library work good, but in doesn't available in Android...
I try figure out which way i should use instead of, but it any suggestion... I am almost sure that it should be a library which allow copy files in one go.
If someone know say please, i am sure it will be very helpful answer for loads of people.
Thanks!
Well with commons-io, you can do this
FileInputStream source = null;
FileOutputStream destination = null;
try {
source = new FileInputStream(new File(/*...*/));
destination = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), /*...*/);
IOUtils.copy(source, destination);
} finally {
IOUtils.closeQuietly(source);
IOUtils.closeQuietly(destination);
}
Just add
compile 'org.apache.directory.studio:org.apache.commons.io:2.4'
to the build.gradle file
try this code
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class CopyFile {
public static void main(String[] args) {
File sourceFile = new File(
"/Users/Neel/Documents/Workspace/file1.txt");
File destFile = new File(
"/Users/Neel/Documents/Workspace/file2.txt");
/* verify whether file exist in source location */
if (!sourceFile.exists()) {
System.out.println("Source File Not Found!");
}
/* if file not exist then create one */
if (!destFile.exists()) {
try {
destFile.createNewFile();
System.out.println("Destination file doesn't exist. Creating
one!");
} catch (IOException e) {
e.printStackTrace();
}
}
FileChannel source = null;
FileChannel destination = null;
try {
/**
* getChannel() returns unique FileChannel object associated a file
* output stream.
*/
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (source != null) {
try {
source.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (destination != null) {
try {
destination.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Use this utility class to read/write file in sdcard:
public class MyFile {
String TAG = "MyFile";
Context context;
public MyFile(Context context){
this.context = context;
}
public Boolean writeToSD(String text){
Boolean write_successful = false;
File root=null;
try {
// check for SDcard
root = Environment.getExternalStorageDirectory();
Log.i(TAG,"path.." +root.getAbsolutePath());
//check sdcard permission
if (root.canWrite()){
File fileDir = new File(root.getAbsolutePath());
fileDir.mkdirs();
File file= new File(fileDir, "samplefile.txt");
FileWriter filewriter = new FileWriter(file);
BufferedWriter out = new BufferedWriter(filewriter);
out.write(text);
out.close();
write_successful = true;
}
} catch (IOException e) {
Log.e("ERROR:---", "Could not write file to SDCard" + e.getMessage());
write_successful = false;
}
return write_successful;
}
public String readFromSD(){
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"samplefile.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
}
return text.toString();
}
#SuppressLint("WorldReadableFiles")
#SuppressWarnings("static-access")
public Boolean writeToSandBox(String text){
Boolean write_successful = false;
try{
FileOutputStream fOut = context.openFileOutput("samplefile.txt",
context.MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(text);
osw.flush();
osw.close();
}catch(Exception e){
write_successful = false;
}
return write_successful;
}
public String readFromSandBox(){
String str ="";
String new_str = "";
try{
FileInputStream fIn = context.openFileInput("samplefile.txt");
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader br=new BufferedReader(isr);
while((str=br.readLine())!=null)
{
new_str +=str;
System.out.println(new_str);
}
}catch(Exception e)
{
}
return new_str;
}
}
Note you should give this permission in the AndroidManifest file.
Here permision
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
For more details visit : http://www.coderzheaven.com/2012/09/06/read-write-files-sdcard-application-sandbox-android-complete-example/
Android developer official Docs
I was trying to write a key value pair to a chat.properties file in java .My function to do so is something like this :
public void WritePropertiesFile() throws FileNotFoundException, IOException {
File file =
new File("C:\\Users\\admin\\Desktop\\SharedCrpto1\\web\\chat.properties");
Properties configProperty = new Properties();
InputStream in = new FileInputStream(file);
configProperty.load(in);
configProperty.setProperty("newKey", "newValue");
in.close();
OutputStream outt = new FileOutputStream(file);
configProperty.store(outt, "my data");
outt.close();
}
But its not working and the data is not being entered in the file.Please help to resolve the problem.
Try this code:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
public class MakeEntryInPropertyFile {
public static void main(String[] args) {
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream("C:\\Users\\admin\\Desktop\\SharedCrpto1\\web\\chat.properties");
prop.setProperty("newKey", "newValue");
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
I was trying an exercise of deleting lines from a file not starting with a particular string.
The idea was to copy the desired lines to a temp file, delete the original file and rename the temp file to original file.
My question is I am unable to rename a file!
tempFile.renameTo(new File(file))
or
tempFile.renameTo(inputFile)
do not work.
Can anyone tell me what is going wrong? Here is the code:
/**
* The intention is to have a method which would delete (or create
* a new file) by deleting lines starting with a particular string. *
*/
package com.dr.sort;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class RemoveLinesFromFile {
public void removeLinesStartsWith(String file, String startsWith, Boolean keepOrigFile) {
String line = null;
BufferedReader rd = null;
PrintWriter wt = null;
File tempFile = null;
try {
// Open input file
File inputFile = new File(file);
if (!inputFile.isFile()) {
System.out.println("ERROR: " + file + " is not a valid file.");
return;
}
// Create temporary file
tempFile = new File(file + "_OUTPUT");
//Read input file and Write to tempFile
rd = new BufferedReader(new FileReader(inputFile));
wt = new PrintWriter(new FileWriter(tempFile));
while ((line = rd.readLine()) != null) {
if (line.substring(0, startsWith.length()).equals(startsWith)) {
wt.println(line);
wt.flush();
}
}
rd.close();
if (!keepOrigFile) {
inputFile.delete();
if (tempFile.renameTo(new File(file))) {
System.out.println("OK");
} else {
System.out.println("NOT OK");
}
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
finally {
if (tempFile != null && tempFile.isFile()) {
wt.close();
}
}
}
}
I guess you need to close your PrintWriter before renaming.
if (line.substring(0, startsWith.length()).equals(startsWith))
should instead be the opposite, because we don't want the lines that are specified to be included.
so:
if (!line.substring(0, startsWith.length()).equals(startsWith))