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();
}
}
}
Hi I have same problem by Writing String ArrayList to file and Reading.
This is my code for writing
File SettingsPath = getFilesDir();
String strSettingsPath = SettingsPath.toString() + "/settings.txt";
File file = new File (strSettingsPath);
if (!file.exists()) {
File removeFile = new File(strSettingsPath.toString());
boolean deleted = removeFile.delete();
}
try {
FileOutputStream fos =
new FileOutputStream(
new File(strSettingsPath));
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this.strSettings);
os.close();
Log.v("","File has been written");
} catch(Exception ex) {
ex.printStackTrace();
}
And this is for Reading
public void reader(View v) throws FileNotFoundException {
File SettingsPath = getFilesDir();
String strSettingsPath = SettingsPath.toString() + "/settings.txt";
List<String> Settings = new ArrayList<String>();
BufferedReader readerL = new BufferedReader(new FileReader(strSettingsPath));
String line;
try{
//line = readerL.readLine();
while ((line = readerL.readLine()) != null) {
Settings.add(line);
System.out.println("The Setting line is " + Settings);
}
readerL.close();
}catch (IOException e){
e.printStackTrace();
}
By reading I get This
The Setting line is [����sr��java.util.ArrayListx����a���I��sizexp������w������t��]
The Setting line is [����sr��java.util.ArrayListx����a���I��sizexp������w������t��, test#test.comt��passwordt�� itdguccgjx]
and I need like this
test#test.com
password
itdguccgjx
What is wrong?
Sorry for my bad English.
Hi
I will like this.
Textbox1
Textbox2
Textbox3
.......
If I will get value of arraylist.get(1).tostring I get Textbox2
I need to read a file in the sd card in my android device and write the contents of this file into another file in the sd card which is already existing.
Here is my code to read a file anywhere in the sdcard.
public String readFromFile(String fileName) {
String ret = "";
try {
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard, fileName);
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
if ( bufferedReader != null ) {
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
Can some one please tell me how can I copy the contents of this file into another file on sdcard after reading.
I do not wish to append but to overwrite the contents of the file.
I need a method in this format
void writeFile(String fileName, String Data){
//code to overwite with given data
}
Can someone please help me
Thanks in advance.
void writeFile(String fileName, String data) {
File outFile = new File(Environment.getExternalStorageDirectory(), fileName);
FileOutputStream out = new FileOutputStream(outFile, false);
byte[] contents = data.getBytes();
out.write(contents);
out.flush();
out.close();
}
The most important part is the false in the FileOutputStream constructor. The second parameter is append. If set to false, the file will be overwritten if it exists.
I have a text file is conten.txt which has
101,1,123
102,1,234
I am using Android to update that text file. With a input as "102", I want to update second line with information is "2,234". So it will be
102,2,234
Finally, the content in text file will be
101,1,123
102,2,234
Is it possible to do it in Android? This is my current work. However, tt only writes a new line in the file
String whole_content="102,2,234";
File file = new File(getApplicationContext().getFilesDir(), "conten.txt");
String filepath = Environment.getExternalStorageDirectory().getPath();
FileOutputStream outputStream;
try {
outputStream = openFileOutput("conten.txt", Context.MODE_PRIVATE);
outputStream.write(whole_content.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Yes it's possible! Simply, you could create a string of total file content and replace all the occurrence in the string and write that string to that file again.
File log= new File("yourFile");
String search = "102"; //Like you said
try{
FileReader fr = new FileReader(log);
String s;
String totalStr = "";
try (BufferedReader br = new BufferedReader(fr)) {
while ((s = br.readLine()) != null) {
if(s.contain(search)) {
s = search + "," + "yourReplaceString"; //You can extract it from your input
}
totolStr += s;
}
FileWriter fw = new FileWriter(log);
fw.write(totalStr);
fw.close();
}
}catch(Exception e){
e.printStackTrace();
}
What's wrong with the code? I added the permission already. Logcat isn't printing the message it's supposed to show.
I'm guessing I have to use a filestream?
public class Run {
int abc = 2;
int[] myIntArray = {1,2,3};
String texts = "abcabac";
//Person p = new Person();
Paragraph p = new Paragraph(abc, texts, myIntArray);
Serializer serializer = new Persister();
File file = new File("paragraphs.xml");
private final static String TAG = Run.class.getCanonicalName();
String a = "writeing something nothing";
// Now write the level out to a file
Serializer serial = new Persister();
//File sdDir = Environment.getExternalStorageDirectory(); should use this??
//File sdcardFile = new File("/sdcard/paragraphs.xml");
File sdcardFile = new File(Environment.getExternalStorageDirectory().getPath());
{
try {
serial.write(p, sdcardFile);
} catch (Exception e) {
// There is the possibility of error for a number of reasons. Handle this appropriately in your code
e.printStackTrace();
}
Log.i(TAG, "XML Written to File: " + sdcardFile.getAbsolutePath());
}
I have samsung galaxy s3 with android 4.1.2. My internal phone memory is named sdcard0 and my external card extSdCard.
Environment.getExternalStorageDirectory()
So the above returns the path of sdcard0 which is internal phone memory
In such cases to get the actual path you can use the below
String externalpath = new String();
String internalpath = new String();
public void getExternalMounts() {
Runtime runtime = Runtime.getRuntime();
try
{
Process proc = runtime.exec("mount");
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
String line;
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
if (line.contains("secure")) continue;
if (line.contains("asec")) continue;
if (line.contains("fat")) {//external card
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
externalpath = externalpath.concat("*" + columns[1] + "\n");
}
}
else if (line.contains("fuse")) {//internal storage
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
internalpath = internalpath.concat(columns[1] + "\n");
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("Path of sd card external............"+externalpath);
System.out.println("Path of internal memory............"+internalpath);
}
Once you get the path you can use the below.
Try the below
String filename = "filename.xml";
File file = new File(Environment.getExternalStorageDirectory(), filename);
//Instead of Environment.getExternalStorageDirectory() you can use internalpath or externalpath from the above code.
FileOutputStream fos;
byte[] data = new String("data to write to file").getBytes();
try {
fos = new FileOutputStream(file);
fos.write(data);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
//to get sdcard path
String sdcardpath = Environment.getExternalStorageDirectory().getPath();
//to write a file in sd card
File file = new File("/sdcard/FileName.txt");
if (!file.exists()) {
file.mkdirs();
}
Permission to add in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
you have to do
filename is test.xml,text.jpg or test.txt
File sdcardFile = new File(Environment.getExternalStorageDirectory()+"/"+filename);
cehck this link.
for more detail about External Storage