I am currently developing an application that reads,writes,updates,deletes json file.i have 4 json files namely data.json(to store name,address,area,pin),image.json(to store image name),location.json(to store latitute,longitude) and final.json that merges the above json files.final.json will combine all data from 3 files to make a single record.In a activity I need to read the name,date,time of all records stored in final.json in different radio buttons. I am unable to read only the name,date,time from a record stored in temp.json as temp.json contains latitute,longitude,image name,name,address,pin,area,date,time.Please help me do the following.Also I need to delete only specific record from temp.json file.
This is the code I used to read the text from temp.json.How to read only name,date,time from the file.I am able to read all the parameters
My temp.json looks like
{Record:["latitute":"22.456","longitude":"88.56","image_name":"xyz.jpg","name":"abc","address":"xx","area":""22","pin":"99","date":"03/05/2018" ,"time":"18:08:22"]} {Record:["latitute":"22.456","longitude":"88.56","image_name":"xyz.jpg","name":"abc","address":"xx","area":""22","pin":"99","date":"03/05/2018" ,"time":"18:08:22" ]}
String root = Environment.getExternalStorageDirectory().toString(); //get access to directory path
File myDir = new File(root + "/GeoPark");//create folder in internal storage
myDir.mkdirs();// make directory
File file = new File(myDir, FILENAME);//making a new file in the folder
if(file.exists()) // check if file exist
{
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Set the text
String x=text.toString();
String z=x.replace("{","").replace("date:","").replace("time:","").replace("Record:","").replace("[","").replace("latitude:","").replace("longitude:","").replace("name:","").replace("address:","").replace("pin:","").replace("area:","").replace("image:","").replace("\"","").replace("]","").replace("}","");
String[] y=z.split(",");
//rb1.setText(y[3].toString()+","+y[7].toString()+","+y[8].toString()+""+"");
// rb2.setText(y[11].toString()+","+y[15].toString()+","+y[16].toString());
//rb3.setText(y[19].toString()+","+y[23].toString()+","+y[24].toString());
//rb4.setText(y[27].toString()+","+y[31].toString()+","+y[32].toString());
}
else
{
rb1.setText("Sorry file doesn't exist!!");
}
///////merge code////
static class CopyFileContent {
public static void main(String[] args) {
JSONObject jsonObj2 = new JSONObject();
try {
// Here we convert Object to JSON
jsonObj2.put("date",a.toString());jsonObj2.put("time",c.toString());// Set the first name/pair
} catch (JSONException ex) {
ex.printStackTrace();
}
String root = Environment.getExternalStorageDirectory().toString(); //get access to directory path
File myDir = new File(root + "/GeoPark");//create folder in internal storage
myDir.mkdirs();// make directory
File destFile = new File(myDir, FILENAME11);//making a new file in the folder
/* Source file, from which content will be copied */
File sourceFile1 = new File(myDir,FILENAME12);
File sourceFile2 = new File(myDir,FILENAME13);
File sourceFile3 = new File(myDir,FILENAME14);
/* destination file, where the content to be pasted */
// File destFile = new File(FILENAME);
/* if file not exist then create one */
if (!destFile.exists()) {
try {
destFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
InputStream input1 = null;
InputStream input2 = null;
InputStream input3 = null;
OutputStream output = null;
InputStream input4=null;
try {
/* FileInputStream to read streams */
input1 = new FileInputStream(sourceFile1);
input2 = new FileInputStream(sourceFile2);
input3 = new FileInputStream(sourceFile3);
/* FileOutputStream to write streams */
output = new FileOutputStream(destFile,true);
byte[] buf = new byte[1024];
int bytesRead;
output.write("{Record:[".getBytes());
while ((bytesRead = input1.read(buf)) > 0) {
output.write(buf, 1, bytesRead);
RandomAccessFile f=new RandomAccessFile(destFile,"rw");
long length=f.length()-2;
f.setLength(length);
length=f.length();
f.close();
output.write(",".getBytes());
}
while ((bytesRead = input2.read(buf)) > 0) {
output.write(buf, 1, bytesRead);
RandomAccessFile f=new RandomAccessFile(destFile,"rw");
long length=f.length()-2;
f.setLength(length);
length=f.length();
f.close();
output.write(",".getBytes());
}
while ((bytesRead = input3.read(buf)) > 0) {
output.write(buf, 1, bytesRead);
RandomAccessFile f=new RandomAccessFile(destFile,"rw");
long length=f.length()-2;
f.setLength(length);
length=f.length();
f.close();
output.write(",".getBytes());
output.write(jsonObj2.toString().getBytes());
output.write("]}".getBytes());
output.write("\r\n".getBytes());
output.write("\r\n".getBytes());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (null != input1) {
input1.close();
}
if (null != input2) {
input2.close();
}
if (null != input3) {
input3.close();
}
if (null != output) {
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Related
Aim:- I have to merge 3 json files into 1 json file.I need to append text to the output file after removing last character from the output file.
NOTE:- I have done this to merge 3 json files into 1 json file.I want to append text into the output file.This code appends text but does not remove the last }.Can anyone help me with the code.Thank You in advance and have a good day in advance.
I have a record of json objects for name,email,lat,lon,date.This fields are in different json files.I have merged them into 1 json file.This job is accomplished.
EXPECTED OUTPUT:- when i append the next record i want the json file to look like
{Record:[{"name1","val","date1","val","lat1","val"..}],[{"name2","val","date2","val","lat2","val"...}]}
OUTPUT ACHIEVED:-
{Record:[{"name1","val","date1","val","lat1","val"..}],{Record:[{"name2","val","date2","val","lat2","val"...}]}
Code:-
static class CopyFileContent {
public static void main(String[] args) {
String root = Environment.getExternalStorageDirectory().toString(); //get access to directory path
File myDir = new File(root + "/GeoPark");//create folder in internal storage
myDir.mkdirs();// make directory
File destFile = new File(myDir, FILENAME11);//making a new file in the folder
/* Source file, from which content will be copied */
File sourceFile1 = new File(myDir, FILENAME12);
File sourceFile2 = new File(myDir, FILENAME13);
File sourceFile3 = new File(myDir, FILENAME14);
/* destination file, where the content to be pasted */
// File destFile = new File(FILENAME);
/* if file not exist then create one */
if (!destFile.exists()) {
try {
destFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
InputStream input1 = null;
InputStream input2 = null;
InputStream input3 = null;
OutputStream output = null;
InputStream input4 = null;
try {
/* FileInputStream to read streams */
input1 = new FileInputStream(sourceFile1);
input2 = new FileInputStream(sourceFile2);
input3 = new FileInputStream(sourceFile3);
/* FileOutputStream to write streams */
output = new FileOutputStream(destFile, true);
byte[] buf = new byte[1024];
int bytesRead;
output.write("{Record:[{".getBytes());
while ((bytesRead = input1.read(buf)) > 0) {
output.write(buf, 1, bytesRead);
RandomAccessFile f = new RandomAccessFile(destFile, "rw");
long length = f.length() - 2;
f.setLength(length);
length = f.length();
f.close();
output.write(",".getBytes());
}
while ((bytesRead = input2.read(buf)) > 0) {
output.write(buf, 1, bytesRead);
RandomAccessFile f = new RandomAccessFile(destFile, "rw");
long length = f.length() - 2;
f.setLength(length);
length = f.length();
f.close();
output.write(",".getBytes());
}
while ((bytesRead = input3.read(buf)) > 0) {
output.write(buf, 1, bytesRead);
RandomAccessFile f = new RandomAccessFile(destFile, "rw");
long length = f.length() - 2;
f.setLength(length);
length = f.length();
f.close();
output.write(",".getBytes());
output.write(b.getBytes());
output.write(d.getBytes());
output.write("}]}".getBytes());
RandomAccessFile f1=new RandomAccessFile(destFile,"rw");
long length1= f1.length()-1;
f1.setLength(length1);
f1.close();
output.write(",".getBytes());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != input1) {
input1.close();
}
if (null != input2) {
input2.close();
}
if (null != input3) {
input3.close();
}
if (null != output) {
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In some cases you need a deep merge, merge the contents of fields with identical names (just like when copying folders in Windows). This function may be helpful:
/**
* Merge "source" into "target". If fields have equal name, merge them recursively.
* #return the merged object (target).
*/
public static JSONObject deepMerge(JSONObject source, JSONObject target) throws JSONException {
for (String key: JSONObject.getNames(source)) {
Object value = source.get(key);
if (!target.has(key)) {
// new value for "key":
target.put(key, value);
} else {
// existing value for "key" - recursively deep merge:
if (value instanceof JSONObject) {
JSONObject valueJson = (JSONObject)value;
deepMerge(valueJson, target.getJSONObject(key));
} else {
target.put(key, value);
}
}
}
return target;
}
public static void main(String[] args) throws JSONException {
JSONObject a = new JSONObject("{offer: {issue1: value1}, accept: true}");
JSONObject b = new JSONObject("{offer: {issue2: value2}, reject: false}");
System.out.println(a+ " + " + b+" = "+JsonUtils.deepMerge(a,b));
}
If you want to merge them, so e.g. a top level object has 4 keys (key1, Key2, Key3, Key4), I think you have to do that manually:
JSONObject merged = new JSONObject(Obj1, JSONObject.getNames(Obj1));
for(String key : JSONObject.getNames(Obj2))
{
merged.put(key, Obj2.get(key));
}
I want use sendFileMessage in sendbird api. It need file value and I want use this file from drawable (or assets). sendBird API
this is snipped code from sendbird
Hashtable<String, Object> info = Helper.getFileInfo(getActivity(), uri);
final String path = (String) info.get("path");
File file = new File(path);
String name = file.getName();
String mime = (String) info.get("mime");
int size = (Integer) info.get("size");
sendFileMessage(file, name, mime, size, "", new BaseChannel.SendFileMessageHandler() {
public void onSent(FileMessage fileMessage, SendBirdException e) {
if (e != null) {
return;
}
mAdapter.appendMessage(fileMessage);
mAdapter.notifyDataSetChanged();
}
});
This code working well which I got uri from open image intent. but I want to use to other purpose and I want to replace this code
File file = new File(path);
become something like
File file = new File(<path or uri from drawable or assets>);
I have tried with uri
Uri uri = Uri.parse("android.resource://com.package.name/raw/filenameWithoutExtension");
File file = new File(uri.getPath());
with inputStream
try {
File f=new File("file name");
InputStream inputStream = getResources().openRawResource(R.raw.myrawfile);
OutputStream out=new FileOutputStream(f);
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0)
out.write(buf,0,len);
out.close();
inputStream.close();
}
catch (IOException e){}
always failed in getting file and return error code ERR_REQUEST_FAILED 800220
Have you tried like below?
String fileName = FILE_NAME;
File cachedFile = new File(this.getActivity().getCacheDir(), fileName);
try {
InputStream is = getResources().openRawResource(R.raw.sendbird_ic_launcher);
FileOutputStream fos = new FileOutputStream(cachedFile);
byte buf[] = new byte[1024];
int len;
while ((len = is.read(buf)) > 0)
fos.write(buf, 0, len);
fos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
groupChannel.sendFileMessage(cachedFile, fileName, "image/jpg", (int) cachedFile.length(), "", new BaseChannel.SendFileMessageHandler() {
#Override
public void onSent(FileMessage fileMessage, SendBirdException e) {
}
});
This works for me.
There is an image file inside a directory. How to copy this image file into another directory that was just created ? The two directories are on the same internal storage of the device :)
You can use these functions. The first one will copy whole directory with all children or a single file if you pass in a file. The second one is only usefull for files and is called for each file in the first one.
Also note you need to have permissions to do that
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Functions:
public static void copyFileOrDirectory(String srcDir, String dstDir) {
try {
File src = new File(srcDir);
File dst = new File(dstDir, src.getName());
if (src.isDirectory()) {
String files[] = src.list();
int filesLength = files.length;
for (int i = 0; i < filesLength; i++) {
String src1 = (new File(src, files[i]).getPath());
String dst1 = dst.getPath();
copyFileOrDirectory(src1, dst1);
}
} else {
copyFile(src, dst);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.getParentFile().exists())
destFile.getParentFile().mkdirs();
if (!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
If you want to copy image programtically then use following code.
File sourceLocation= new File (sourcepath);
File targetLocation= new File (targetpath);
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
** Use FileUtils This Is Simple Fast And Best method and Download Jar file from here**
public void MoveFiles(String sourcepath) {
File source_f = new File(sourcepath);
String destinationPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/WhatsappStatus/yourfilename.mp4";
File destination = new File(destinationPath);
try
{
FileUtils.copyFile(source_f , destination);
}
catch (IOException e)
{
e.printStackTrace();
}
}
Go To Link For FileUtils Jar
i have build an application the user can download with one button click an image and attachments text file (in two separate folder one folder for store image and the other for text file )
now I would like build an listview for display this data, each row contain image (ImageView) and name of image (textView) and when user click on it i would like display the attachments text file
DownloadFile code :
#Override
protected Void doInBackground(String... strings) {
String filetxtUrl = strings[0];
String filetxtName = strings[1];
String fileImageUrl = strings[2];
String fileImageName = strings[3];
String extStorageDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(); //(Environment.DIRECTORY_DOWNLOADS)
File folder = new File(extStorageDirectory, "folder");
if (!folder.exists()) {
folder.mkdirs();
}
File folder1 = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"
+ "folder" , "txt");
if (!folder1.exists()) {
folder1.mkdirs();
}
File TxtFile = new File(folder1, filetxtName);
File folder3 = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"
+ "folder" , "Image");
if (!folder3.exists()) {
folder3.mkdirs();
}
File ImageFile = new File(folder3, fileImageName);
try{
TxtFile.createNewFile();
ImageFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
FileDownloader.downloadFile(filetxtUrl, TxtFile);
FileDownloader.downloadFile(fileImageUrl, ImageFile);
L.m("File Download successufuly in Sdcard0 ");
return null;
}
FileDownloader code :
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
L.m(""+e);
} catch (MalformedURLException e) {
L.m(""+e);
} catch (IOException e) {
L.m(""+e);
}
}
}
I want use the code below to read the the txt files attachment
public void displayOutput()
{
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"/TextFile.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) {
Toast.makeText(getApplicationContext(),"Error reading file!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),"File not found!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
TextView output=(TextView) findViewById(R.id.output);
// Assuming that 'output' is the id of your TextView
output.setText(text);
}
I have been trying to export my database file into the external memory of my android phone by using
private final String DB_NAME = "MemberData";
private final String TABLE_NAME = "MemberDB";
//Get a reference to the database
File dbFile = this.getDatabasePath(DB_NAME);
//Get a reference to the directory location for the backup
File exportDir = new File(Environment.getExternalStorageDirectory(), "myAppBackups");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File backup = new File(exportDir, dbFile.getName());
//Check the required operation String command = params[0];
//Attempt file copy
try {
backup.createNewFile();
fileCopy(dbFile, backup);
} catch (IOException e) {
/*Handle File Error*/
}
private void fileCopy(File source, File dest) throws IOException {
FileChannel inChannel = new FileInputStream(source).getChannel();
FileChannel outChannel = new FileOutputStream(dest).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null) inChannel.close();
if (outChannel != null) outChannel.close();
}
}
It managed to create a directory name "myappsbackup" but my database couldnt be copied over. it is always size 0 and my tables are missing. Is there something wrong with my method of copying?
Here is the code I use to write or backup my SQLite db to the sdcard.
try {
db.open();
File newFile = new File("/sdcard/Your File Name Here");
InputStream input = new FileInputStream(
"/data/data/com.packageNameHere/databases/DB Name Here");
OutputStream output = new FileOutputStream(newFile);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
db.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}