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.
Related
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" />
I know this is duplicate question but there is not available any solution for this. I have used latest API Level 24 and Test on API 23. I have to save image on SD Card with my App Name folder but folder is not created...
I have write following method but it not working
public void actionScreenShot(View view) {
//enable drawing cache true
imageContainer.setDrawingCacheEnabled(true);
imageContainer.buildDrawingCache(true);
//create image from layout
Bitmap bitmap = Bitmap.createBitmap(imageContainer.getDrawingCache());
//String folder_path = getApplicationContext().getFilesDir().getPath() + "/MyAppTest/"; //It's work properly
//String folder_path = getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DCIM) + "/MyAppTest/"; //It's work properly
String folder_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath() + "/MyAppTest"; //It's not work properly
if (checkFile(folder_path)) {
saveFile(new File(folder_path), bitmap);
} else {
File folder = new File(folder_path);
if (folder.mkdirs()) {
saveFile(folder, bitmap);
} else {
Log.d("Directory", " >> not created");
}
}
}
public void saveFile(File folder, Bitmap bitmap) {
boolean success = false;
try {
File file = new File(folder, "temp.png");
if (file.exists()) file.delete();
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
success = checkDatabase(file.getPath());
}catch (Exception e) {
e.printStackTrace();
}
if (success) {
Log.d("FILE", "success");
} else {
Log.d("FILE", "not success");
}
}
public boolean checkFile(String myPath) {
boolean isExist = false;
try {
File file = new File(myPath);
isExist = file.exists();
} catch (Exception e) {
}
return isExist;
}
Permission is given also in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Log Trace as following...
10-05 17:08:09.424 2808-2808/packagename D/Directory >> not created
If any solution available then help me...
Thanks....
here is the simple code to create folder in sdcard
// create a File object for the parent directory
File newFolder = new File("/sdcard/newFolder/");
// have the object build the directory structure, if needed.
newFolder.mkdirs();
// create a File object for the output file
File outputFile = new File(newFolder, filename);
// now attach the OutputStream to the file object, instead of a String
FileOutputStream fos = new FileOutputStream(outputFile);
permission in manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The problem is that you are using API 23 and 24 (Marshmallow).
Google changed the permission strategy from API 23.
Reduce your target version to 22. It will work. If you want 23 or 24 then include code to request permission at run time.
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
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" />
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" />