unable to save the file in the external directory in android. - android

In android, how to write the file in the external directory in the desired folder.
i have use the following coding, but it doesn't seems to work.
File r = Environment.getExternalStorageDirectory();
File oD = new File(root.getAbsolutePath() + File.separator + "web_dir");
if (!outDir.isDirectory()) {
outDir.mkdir();
}
try {
if (!outDir.isDirectory()) {
throw new IOException(
"Unable to create directory");
}
File outputFile = new File(outDir, "web_file");
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
writer.write(new String("hello"));
Toast.makeText(context.getApplicationContext(),
"Successfully saved to: " + outputFile.getAbsolutePath(),
Toast.LENGTH_LONG).show();
writer.close();
} catch (IOException e) {
Log.w("et", e.getMessage(), e);
Toast.makeText(context, e.getMessage() + " Unable to write to external"
+"storage.", Toast.LENGTH_LONG).show();
}

First make sure you have permission in your manifest file to write external storage.
<!-- Depends on your requirements -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Ref: Saving Files - Android Developer Doc
below is the sample code to write file to external storage.
private void writeToSDFile(){
// Find the root of the external storage.
// See http://developer.android.com/guide/topics/data/data- storage.html#filesExternal
File root = android.os.Environment.getExternalStorageDirectory();
tv.append("\nExternal file system root: "+root);
// See http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
File dir = new File (root.getAbsolutePath() + "/download");
dir.mkdirs();
File file = new File(dir, "myData.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println("Hi , How are you");
pw.println("Hello");
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "******* File not found. Did you" +
" add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\n\nFile written to "+file);
}
Hope it will help you..

What's the error message? As Mike said, your are probably missing the correct permission. Add the following to your manifest, as a child of the <manifest> tag:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Related

Cannot save string to file on android

I am trying to create txt file and write to it on sdcard in android. I am getting "Directory not created" error. path.mkdirs() should create needed directories, shouldn't it ? I have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in AndroidManifest.xml and I have turned on storage permission for app.
Android version: 7.0
public void addData(View v) {
wordList.add(inAddWord.getText().toString());
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File file = new File(path, "wordDatabase.txt");
try {
if(!(path.exists() && path.isDirectory())) {
while (!path.mkdir()) {
Log.e("Path", "Directory not created");
}
}
OutputStream os = new FileOutputStream(file);
os.write((inAddWord.getText().toString() + "\n").getBytes());
os.close();
} catch (IOException e) {
e.printStackTrace();
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
On Android 6+ you should add code to ask the user to confirm the permissions you request in manifest.
Google for runtime pemissions.

getting a FileNotFoundException using the following code

I am trying to create a logfile of RSSI values and RSSI values once a filter has been applied. I do not want to use the android logfile. I want to use a text file that I can export to excel. This is the code that I have written. I am new to android, but have some java experience.
state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
Log.d("MainActivity", "MEDIA_MOUNTED is true");
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOCUMENTS);
File file = new File(path, "RSSI.txt");
try {
pw = new PrintWriter(new FileWriter(file), true);
pw.print(beacon.getRssi());
pw.print(kalman.kalman(rssis));
pw.println();
pw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
you can try creating a new file if it doesn't exist
if(!file.exists())
{
file.createNewFile()
// you can start writing to file from here.
}
make sure to add permission to read and write from the external storage in the manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Where does the file get saved using "File file = new file(filename)" in Android

I am writing an android application. In the MainActivity.java, I created a method to write and then read contents from a file. These code runs successfully I and can store the data in a file named abc.txt, but I cannot find the written file in ES File Explorer.
public void writeInIt(View view) {
try {
String Message = editText.getText().toString();
final File myFile = new File("abc.txt");
if (!myFile.exists()) {myFile.createNewFile(); }
FileOutputStream outputStream = new FileOutputStream(myFile);
outputStream.write(Message.getBytes());
outputStream.close();
editText.setText("");
Toast.makeText(getApplicationContext(), "Message Saved", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
Where does it save the file? Why I can't I search it through the File Explorer?
Ref to "http://developer.android.com/reference/java/io/File.html", if i include path, it will definitely store in that path location. However, if I not locate the dir, it can still store in device, but where does the file actually save???
"File file = new file(filename)"
this code does not save anything, it only cretes a class wrapper for file or director path. The closest method to actually create file would be to use file.createNewFile method.
There is guide for writing files from google: Saving Files
[edit]
following code generates exception "open failed: EROFS (Read-only file system)":
File fl = new File("test12.txt");
try {
fl.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
In Android manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
this is the code :
public void generateNoteOnSD(String sFileName, String sBody){
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
importError = e.getMessage();
iError();
}
}
You can find this file in device manager.
Click your device (file symbol)
/data/user/0/com.example.myapplication/files and than follow this path

Unable to write to external SD Card in Android

I am trying to write files in the external SD card folder. Even after having set the required permission in the manifest file, I am unable to write on the external SD card.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Code:
String path = "/mnt/extsd/nit.txt";
File myFile = new File(path);
if (!myFile.exists()) {
try {
myFile.createNewFile();
} catch(Exception e)
{
txtText.setText("Failed-" + e.getMessage());
e.printStackTrace();
}
}
try {
FileOutputStream fostream = new FileOutputStream(myFile);
OutputStreamWriter oswriter = new OutputStreamWriter(fostream);
BufferedWriter bwriter = new BufferedWriter(oswriter);
bwriter.write("Hi welcome ");
bwriter.newLine();
bwriter.close();
oswriter.close();
fostream.close();
txtText.setText("success");
} catch(Exception e)
{
txtText.setText("Failed-" + e.getMessage());
e.printStackTrace();
}
On the other hand when I use ES File Explorer and try to create a file, it creates it without any issues.
Don't use the absolute path String path = "/mnt/extsd/nit.txt"; because you never know about android device being used by users. Rather you can get the external storage directory path by using Environment.getExternalStorageDirectory().toString().
You should be able to call Environment.getExternalStorageDirectory() to get the root path to the SD card and use that to create a FileOutputStream. From there, just use the standard java.io routines.
File log = new File(Environment.getExternalStorageDirectory(), "your_file_name.txt");
try {
out = new BufferedWriter(new FileWriter(log.getAbsolutePath(), false));
out.write("any data");
} catch (Exception e) {
}
And don't forget to close the streams.
First check sd-card is available or not.
String state = Environment.getExternalStorageState();
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
if (Environment.MEDIA_MOUNTED.equals(state))
{
File folder = folder = new File(extStorageDirectory, "FolderName");
if(!folder.exists())
{
folder.mkdir();//making folder
}
File file = new File(folder,"Filename");//making file
}
Please try this code, it work in my application.

No such file or directory when trying to save file

For an App I am developing, I want to write some text to a text file on the SD card. I've tried to do that with the code below. This gives an error but I can't see why. As far as I can tell I have followed all the examples on the web perfectly. In logcat I see the first log, but not the second one so the problem is in the creation of the file. Do you guys have an idea what's going wrong?
public void saveDataToFile(String data, String fileName) {
Log.d("Checks", "Trying to save data");
try {
// Set up the file directory
String filePath = Environment.getExternalStorageDirectory().toString() + "/Data Folder";
File fileDirectory = new File(filePath);
fileDirectory.mkdirs();
Log.d("Checks", "Directory created");
// Set up the file itself
File textFile = new File(fileDirectory, fileName);
textFile.createNewFile();
Log.d("Checks", "File created");
// Write to the file
FileOutputStream fileOutputStream = new FileOutputStream(textFile);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
outputStreamWriter.append(data);
outputStreamWriter.close();
fileOutputStream.close();
Toast.makeText(mContext, "Done writing to SD card", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
EDIT:
Turns out I had forgotten to add the right permission to the manifest. It works now!
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Did you declare the proper uses permissions to access and write to the External SD card ?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Categories

Resources