Write to a file android - android

I am trying to write some date data in a file with with function:
public void writeSettings(Context context, String data){
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try {
fOut = openFileOutput("settings.dat",MODE_PRIVATE);
osw = new OutputStreamWriter(fOut);
osw.write(data);
osw.flush();
Toast.makeText(context, "Settings saved",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Settings not saved",Toast.LENGTH_SHORT).show();
}
finally {
try {
osw.close();
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the blog where I found this code, it is said my file is stored in:
/data/data/PACKAGE_NAME/files/settings.dat
But I cannot find it on my phone! Where is this data folder?

In phone (Device) you don't have root privileges,so you can't see /data/data/ directory using eclipse->DDMS->File Explorer,
SO if you want to just see whether your file is created or not you can use ./adb shell command (for linux) adb shell (for windows)
Or try this on emulator and check with eclipse -> DDMS -> File Explorer...

You don not have access to /data folder in your phone unless you have root privileges.
You can test your app in emulator, data folder in emulator is accessable.

Have you tried to add permissions WRITE_SECURE_SETTINGS and/or WRITE_SETTINGS?

If you are using eclipse ide, find DDMS Window and click File Explorer. Search for /data/data/Package_Name/files

Related

AOSP: Write a file on /data directory

I want to write a file on "/data" directory. I have rooted my device and setenforce 0. However, I am getting:
W/System.err: java.io.FileNotFoundException: data/MyDoople.txt
(Permission denied)
Here is my code (it works for sdcard):
String filename= "MyDoople.txt";
try
{
File f = new File("data/"+File.separator+filename);
FileOutputStream fOut = new FileOutputStream(f);
OutputStreamWriter myOutWriter = new OutputStreamWriter(
fOut);
myOutWriter.append("Mytest");
myOutWriter.close();
fOut.close();
}
catch(Exception e)
{
e.printStackTrace();
}
Do I have to add any policy to make it work?
Because the permission of the data directory is rwxrwx--x, user system, group system, and the running user of your app is a common user, not a system user, so the app unable to read and write the /data directory directly.
Two ways can be referred to:
1: If you have a platform certificate, declare android:sharedUserId="android.uid.system" in AndroidManifest.xml, and use the platform certificate to re-sign the app. In this way, the user running your app is the system user, who has read and write permissions to the /data partition.
2: obtain the root permission in the app, and then execute the relevant command, refer to:
public static boolean RootCommand(String command) {
Process process = null;
DataOutputStream os = null;
try {
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(command + "\n");
os.writeBytes("exit\n");
os.flush();
process.waitFor();
} catch (Exception e) {
Log.d("*** DEBUG ***", "ROOT REE" + e.getMessage());
return false;
} finally {
try {
if (os != null) {
os.close();
}
process.destroy();
} catch (Exception e) {
}
}
Log.d("*** DEBUG ***", "Root SUC ");
return true;
}

How to properly write file in android to make it available to ADB?

Actually i have an app that by receiving a specific intent write a specific txt file with a written in it trace.
To write the file i use the following method
public void write(String data, Context context,String filename) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput(filename, Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
And till here all is working fine, the file is written but now i need to pull that file via ADB and here come the issue. As the OutputStreamWriter is set to Context.MODE_PRIVATE adb pull command just can't find that file so which would be the best method to write that file in a "public" directory and then be able to pull that file via ADB?
The ADB commands will be sent from a VB.NET programm.

Android Studio - Acces to /storage/emulated/0 from windows explorer and android file manager

I a newbie in android development.
I sure that many people have same issue. I ve a Galaxy S7 phone without SD Card. So no external storage. But i want create file with my app which have to be access from windows explorer to export it.
Note : debbug in USB mode - No virtual device
Of course in my manifest file i ve setted those 2 permissions :
android.permission.WRITE_INTERNAL_STORAGE
android.permission.WRITE_EXTERNAL_STORAGE
To be sure i ve created a file i use this write method and the following read method :
File root = this.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
File customFolder = new File(root.getAbsolutePath() + "/CustomFolder");
customFolder.mkdirs();
file = new File(customFolder, "myData.txt");
// Must catch FileNotFoundException and IOException
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println("Howdy do to you,");
pw.println("and the horse you rode in on.");
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "File not found");
} catch (IOException e) {
e.printStackTrace();
Log.i(TAG, "I/O exception");
}
To read myData.txt
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while (true) {
line= br.readLine();
if (line== null) break;
tv.append("\n" + " " + line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
So all method are OK, but when i browse my files system to get the created file myData.txt, I can't find it !!
Most of the apps we install have their own folder on the root, like Snapchat, Whatsapp etc etc
I d like to make the same thing, what is the way to write file in:
ROOT --> MyApplicationName --> CustomFolder
Thanks for your help :)
I finally found a solution adding a MediaScannerConnection.scanFile() method.
MediaScannerConnection.scanFile(getApplicationContext(),new String[]{file.getAbsolutePath()},null,new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
// Do something here if you want
}});
But this solution don't totally fit me, because the storage folder is :
Android/data/donain_name/files/Documents/CustomFolder
I'd like to have same result like whatsapp application which can have a folder in the internal storage root.
The result i want is :
MyApplication/CustomeFolder

Android App: Save a txt file that can be accessed through Explorer

I'm trying to create a txt file during the operation of my App which I then want to download onto my computer and assess the contents.
I've try both on the internal and external storage but I am still unable to find the text file after (when my tablet is plugged into my computer).
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("orp.txt",Context.MODE_WORLD_WRITEABLE));
outputStreamWriter.write(data);
outputStreamWriter.close();
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"orp2.txt");
String tempS = file.getAbsolutePath();
file.setReadable( true, false );
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(data);
bw.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
I have found been able to find either ("orp.txt" or "orp2.txt"), but also I do not receive any error during the running of the app, and the app is able to open "orp.txt" at a later time, so I know is has been created.
I cant find files created unless using Eclipse file explorer, or maybe its the media scan that has to be triggered, can be done by restarting the device. Scans the files available on the device.
It may be the directory, this is what I do in my code.
File f = new File(cxt.getExternalFilesDir(filepath), fileName);
f.createNewFile();
FileWriter writer = new FileWriter(f);
writer.append(manNo+System.getProperty("line.separator"));
writer.append(dateTime);
writer.flush();
writer.close();
Thanks for the input but I found the answer was to do with the media scanner, "orp2.txt" appeared in my download folder after I restarted the device.
This answer and blog post helped
Android: save file to downloads that can be viewed later

how to write json data to a file in android

Can someone explain what is going wrong here I am using following function
public void WriteSettings(Context context, String data){
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try{
fOut = context.openFileOutput("schemas.json",Context.MODE_APPEND);
osw = new OutputStreamWriter(fOut);
osw.write(data);
osw.flush();
Toast.makeText(context, data+"Data",Toast.LENGTH_SHORT).show();
Toast.makeText(context, "Settings saved",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Settings not saved",Toast.LENGTH_SHORT).show();
}
finally {
try {
osw.close();
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And calling with once my http request is completed
JSONObject json_res = currentDFD.getJSONObject("result");
WriteSettings(getBaseContext(),json_res.toString());
The result is alerted in toast however not written to the file
the file is located in assets folder
thanks in advance
AFAIK You can't. The assets folder is read-only at runtime.
Pick a different location to save your data, see Data Storage in Android for more information.
The assets folder is like folders res, src, gen, etc. These are all useful to provide different files as input to build system to generate APK file for your app.
All these are read-only while your app is running. At run-time you can only write to SD card.

Categories

Resources