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.
Related
I searched and tried a lot before asking this.
But all the code that I'm trying is not working.
I want the file to be stored in the download folder and be accessible from the user also if he uninstalls the app.
I also tried using opencsv library. Could you provide a tested way to create a csv or txt file and store to download folder?
Save to to publicDir(Downloads folder) you first need permission.WRITE_EXTERNAL_STORAGE
check docs
Note this won't work without permmissions
private void saveData(){
String csv_data = "";/// your csv data as string;
File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
//if you want to create a sub-dir
root = new File(root, "SubDir");
root.mkdir();
// select the name for your file
root = new File(root , "my_csv.csv");
try {
FileOutputStream fout = new FileOutputStream(root);
fout.write(csv_data.getBytes());
fout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
boolean bool = false;
try {
// try to create the file
bool = root.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
if (bool){
// call the method again
saveData()
}else {
throw new IllegalStateException("Failed to create image file");
}
} catch (IOException e) {
e.printStackTrace();
}
}
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
I have a very specific issue - I am trying to write to external storage on an Asus Nexus 7, but it is writing to the emulated directory on the device.
Here is the code I am using:
public static void writeExternalMedia(Context context) {
if(isExternalStorageWritable()) {
String content = "hello world";
File filedir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/test");
filedir.mkdir();
File file;
FileOutputStream outputStream;
try {
file = new File(filedir, "test.txt");
if (!file.exists()) {
file.createNewFile();
}
outputStream = new FileOutputStream(file);
outputStream.write(content.getBytes());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Whenever I restart the device, the directories appear under the device when plugged in, which is what I would expect to happen when the function above gets executed.
I have tried searching for a solution and cannot find the answer to my question.
I made two methods. One for creating a file and one for appending to it. I think the issue is that you're not calling createNewFile.
private File CreateFile(String fileName)
{
File file = new File(this.getFilesDir(), fileName);
try
{
if(!file.exists())
{
file.createNewFile();
}
}
catch (IOException e)
{
e.printStackTrace();
}
return file;
}
private void appendToFile(String file, String content)
{
try
{
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(this.openFileOutput(file, this.MODE_APPEND));
outputStreamWriter.append(content + "\n");
outputStreamWriter.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Alright after much searching and testing I finally came across a solution, linked via one of the other answers.
https://stackoverflow.com/a/28448843/979220
The solution was to scan the media files, which causes the files to propagate to the external storage, rather than staying in the emulated storage.
I am trying to retrieve a file via FTP but I am getting the following error in LogCat:
java.io.FileNotFoundException :/config.txt (read-only file system)
I have verified that the file exists on the server, and I can read it by double clicking it in a web browser.
Can anyone help please? Here is the code I am using:
FTPClient client = new FTPClient();
FileOutputStream fos = null;
try {
client.connect("xxx.xxx.xxx.xxx");
client.enterLocalPassiveMode();
client.login("user", "pass");
//
// The remote file to be downloaded.
//
String filename = "config.txt";
fos = new FileOutputStream(filename);
//
// Download file from FTP server
//
client.retrieveFile("/" + filename, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
You cannot save files on the root of the phone. Use Environment.getExternalStorageDirectory()to get an file object of the SD card's directory and save the file there. Maybe create a directory for it. To do that you need the permission android.permission.WRITE_EXTERNAL_STORAGE.
Sample code:
try {
File external = Environment.getExternalStorageDirectory();
String pathTofile = external.getAbsolutePath() + "/config.txt";
FileOutputStream file = new FileOutputStream(pathTofile);
} catch (Exception e) {
e.printStackTrace();
}
You are trying to read the file in, but you have created an OutputStream, you need to create an inputStream and then read the file from that input stream.
Here is a great article, with come code that is very helpful. This should get you headed in the right direction.
http://www.roseindia.net/java/beginners/java-read-file-line-by-line.shtml
I hope this helps!
Best of luck
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