I have to store data text to SD Card.
This is my code :
try {
File myFile = new File(Environment.getExternalStorageDirectory()+"/mnt/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
In AndroidMainfest i have :
<uses-permission android:name="android.permisson.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I don't understand Why it don't work ?
In Toast reported error :Permission denied?
Please help me .
You can also try this https://github.com/uberspot/AndroidStorageUtils it's a wrapper class/package that makes storage usage in android a bit easier. :) It has a "saveStringOnExternalStorage" method as well.
Try this code must solve issues...
try{
String filename = "filename.txt";
File myFile = new File(Environment.getExternalStorageDirectory(), filename);
if(!myFile.exists())
myFile.createNewFile();
FileOutputStream fos;
byte[] data = txtData.getBytes();
try {
fos = new FileOutputStream(myFile);
fos.write(data);
fos.flush();
fos.close();
}
catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
Related
I want to write a .txt file to the phone so the user can access from file storage
This is what I have so far, but I found out it was only available to my app.
path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
public void Print() {
String print = "text"
printstring(print);
}
public void printstring(String s) {
try {
File file = new File(path, "fileName.txt");
FileOutputStream fileOutputStream = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
bufferedWriter.write(s);
bufferedWriter.close();
outputStreamWriter.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText( MainActivity.getAppContext() , "Toast", 1000).show();
}
}
}
for those that need the answer, I figured it out.
public void printstring(String print) {
try {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "filename.txt");
FileOutputStream fileOutputStream = new FileOutputStream(file);
PrintWriter printWriter = new PrintWriter(fileOutputStream);
printWriter.write(print);
printWriter.close();
fileOutputStream.close();
Toast.makeText(MainActivity.getAppContext(), "save successful", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.getAppContext(), "Toast", Toast.LENGTH_LONG).show();
}
then I need the following in the Manifest
<application android:requestLegacyExternalStorage="true" ... </application>
on top of the user permissions
I am trying to export some data on my app. Even though I set required permission on manifest and deleted build multiple times, it gives the same error. How can I fix it?
FileNotFoundException: /storage/emulated/0/VocAppFile/output.txt (No such file or directory)
The thing is there is no such folder like above in my phone. But /storage/emulated/0/ is the default directory.
My code is this:
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)){
File Root = Environment.getExternalStorageDirectory();
Log.d("Export to", Root.getAbsolutePath());
File Dir = new File(Root.getAbsolutePath()+"/AppFile");
if(!Dir.exists()){
Dir.mkdir();
}
File file = new File(Dir,"output.txt");
try {
FileOutputStream fos = new FileOutputStream(file);
for(String[] d : data){
//data comes ready
fos.write(d[0].getBytes());
fos.write(d[1].getBytes());
}
fos.close();
Toast.makeText(getApplicationContext(), "Data exported",
Toast.LENGTH_SHORT).show();
}catch (FileNotFoundException e){
Log.wtf("My activity", "Error in exporting words");
e.printStackTrace();
}catch (IOException e){
Log.wtf("My activity", "Error in exporting words");
e.printStackTrace();
}
Put this line after File Dir = ...
New Line
file.createNewFile();
Final Code will be like this
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)){
File Root = Environment.getExternalStorageDirectory();
Log.d("Export to", Root.getAbsolutePath());
File Dir = new File(Root.getAbsolutePath()+"/AppFile");
if(!Dir.exists()){
Dir.mkdir();
}
File file = new File(Dir,"output.txt");
file.createNewFile();
try {
FileOutputStream fos = new FileOutputStream(file);
for(String[] d : data){
//data comes ready
fos.write(d[0].getBytes());
fos.write(d[1].getBytes());
}
fos.close();
Toast.makeText(getApplicationContext(), "Data exported",
Toast.LENGTH_SHORT).show();
}catch (FileNotFoundException e){
Log.wtf("My activity", "Error in exporting words");
e.printStackTrace();
}catch (IOException e){
Log.wtf("My activity", "Error in exporting words");
e.printStackTrace();
}
I fixed the problem with following steps 1-2-4 of stackoverflow.com/a/41221852/5488468
So many examples for this question. I tried and still doesn't work.
Test.txt file is created. But no data is written into the test.txt file.
What is wrong with my code? I have permission in the Manifest file as
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Code:
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/PrintFiles";
File file = new File(file_path+"/test.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FileOutputStream fos = null;
try {
fos = openFileOutput(file.getName(), Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] b = {65,66,67,68,69};
fos.write(b);
fos.flush();
fos.close();
Cause, you are creating file in SDCard but writing in Internal Storage. Try as follows...
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/PrintFiles";
File file = new File(file_path+"/test.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] b = {65,66,67,68,69};
fos.write(b);
fos.flush();
fos.close();
From the doc openFileOutput will
Open a private file associated with this Context's application package for writing. Creates the file if it doesn't already exist.
those files are under the.
data > data > your app id > files
but your file is not in internal folder its in external storage..
Change this line
fos = openFileOutput(file.getName(), Context.MODE_PRIVATE);
into
fos=new FileOutputStream(file);
And try..
I want to serialize an object and store it inside sdcard under my project name but I'm getting FileNotFoundException.
My code is written below:
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
File dir = new File(Environment.getExternalStorageDirectory(), FILE_LOCATION + username);
try {
if(!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, FILE_NAME);
fileOutputStream = new FileOutputStream(file);
objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(formList);
objectOutputStream.close();
} catch(IOException ioException) {
ioException.getMessage();
} catch (Exception e) {
e.getMessage();
}
What is the reason for this issue? I'm running in emulator and my application is in android 3.0.
I suspect your filename is invalid, maybe that . in the directory? Or the file-name its self.
Correct me if I'm wrong, but don't you have to create the File before you write to it?
File file = new File(dir, FILE_NAME);
if (!file.exists()) {
file.createNewFile();
}
I would like to share my solution for this since I got a lot of help from Stackoverflow on this issue (by searching for previous answers). My solution resulted for a couple of hours of searching and piecing together solutions. I hope it helps someone.
This will write and read an ArrayList of custom objects to and from External Storage.
I have a class that provides IO to my activities and other classes. Alarm is my custom class.
#SuppressWarnings("unchecked")
public static ArrayList<Alarm> restoreAlarmsFromSDCard(String fileName,
Context context) {
FileInputStream fileInputStream = null;
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();//Alarm is my custom class
//Check if External storage is mounted
if (Environment.getExternalStorageState() != null) {
File dir = new File(Environment.getExternalStorageDirectory(),
"YourAppName/DesiredDirectory");
try {
if (!dir.exists()) {
Log.v("FileIOService", "No Such Directory Exists");
}
File file = new File(dir, fileName);
fileInputStream = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fileInputStream);
alarmList = (ArrayList<Alarm>) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
//Do something here to warn user
}
return alarmList;
}
public static void saveAlarmsToSDCard(String fileName, ArrayList<Alarm> alarmList,Context context) {
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
if (Environment.getExternalStorageState() != null) {
File dir = new File(Environment.getExternalStorageDirectory(),
"YourAppName/DesiredDirectory");
try {
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, fileName);
fileOutputStream = new FileOutputStream(file);
objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(alarmList);
objectOutputStream.close();
} catch (IOException ioException) {
ioException.getMessage();
} catch (Exception e) {
e.getMessage();
}
}else{
//Do something to warn user that operation did not succeed
}
}
I am trying to test for this cache in my asyncTask. How would i go about doing this?
public void putBitmapInDiskCache(URI imageUri, Bitmap avatar) {
File cacheDir = new File(this.getCacheDir(), "thumbnails");
cacheDir.mkdirs();
File cacheFile = new File(cacheDir, ""+imageUri.hashCode());
try {
cacheFile.createNewFile();
FileOutputStream fos = new FileOutputStream(cacheFile);
avatar.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (Exception e) {
Log.e("error", "Error when saving image to cache. ", e);
}
Based on what you have. If prior to your call to createNewFile() you were to check if it exists, you can do whatever needs to be done there
if (cacheFile.exists()) { ... } else { cacheFile.createNewFile() }