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" />
Related
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.
The question is pretty common and I have googled it a few but I still have problems. I have to save in a text file some data for a game that I am trying to develop. This is the code:
if (!isSecond(game[k])) {
//Where I'd like to save the file
File myFile = new File(Environment.getExternalStorageDirectory() + "/flagQuiz/record.txt");
//Try to save my file
try {
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
//correctGuess and TimeElapsed are two integers
myOutWriter.append(String.valueOf(correctGuess) + "-" + String.valueOf(TimeElapsed));
myOutWriter.close();
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
The log cat shows me this kind of error:
I have declared the possibility to save stuff in the SD Card in this way I guess:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Where is the mistake? flagQuiz folder is already created at runtime.
Be sure to check if file.exists() if true then delete it and create new one
else false then just carry on with your try block
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.
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" />
I am trying to write a jpg image to the external SD card. However, I am getting System.err FileNotFoundException: /mnt/sdcard/test.images/temp/savedImage (no such file or directory). Creating the directory also seems to fail and gives a false in LogCat and I also cannot see the folder when looking on my SD card.
My code is as follows:
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File folder = new File(Environment.getExternalStorageDirectory() + "/test.images/temp");
try {
if(!folder.exists()){
boolean dir = new File(Environment.getExternalStorageDirectory() + "/test.images/temp").mkdir();
Log.v("creating directory", Boolean.toString(dir));
}
File imageOutputFile = new File(Environment.getExternalStorageDirectory() + "/test.images/temp", "savedImage");
FileOutputStream fos = new FileOutputStream(imageOutputFile);
Image.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I have permission <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
in the manifest and have cleaned and rebuilt.
Use mkdirs() instead of mkdir().
Guido posted a solution that works for me in the comment. I am going to repeat it just to make sure it can be an answer.