Given this code:
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + "/";
String file = dir + "info.txt";
File newfile = new File(file);
//Environment.getExternalStorageDirectory().toString()= /storage/emulated/0
String msgData="p1000";
FileOutputStream outputStream;
try {
newfile.createNewFile();
outputStream = openFileOutput(file, Context.MODE_PRIVATE);
outputStream.write(msgData.getBytes());
outputStream.close();
} catch (Exception e) {
e.toString();
//e.printStackTrace();
}
When I open file /storage/emulated/0/Documents/info.text, I find it empty while it should have the string "p1000";
why is that?
note: I do not have external storage (external sd card).
thanks.
Do you have WRITE_EXTERNAL_STORAGE Permission in your Manifest?
Try this: FileOutputStream outputStream = new FileOutputStream(file);
If you wanna use internal storage you should not pass a path pointing at the external storage (roughly sd card). In you try-catch block use this line instead:
outputStream = openFileOutput("info.txt", Context.MODE_PRIVATE);
The file will be saved in the directory returned by Context.getFilesDir().
Related
I'm trying to create a file in the internal storage
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
But when i search in /data/data/ i don't find the app dir to see the file presence...why? I try with a context.getApplicationInfo().dataDir() but it don't work it give error. How can i do? What is/are my mistake(s)?
Try something like this,
File path = getFilesDir();
File file = new File(path, filename);
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(string.getBytes());
outputStream.close();
you should probably do a google search before posting.
The file will be located in
data->data->package name->files->filename
File Explorers have no access to the /data directory.
With getFilesDir() you will know the directory where you put your file.
outputStream = context.getFilesDir().openFileOutput(filename, Context.MODE_PRIVATE);
getFilesDir() returns the Absolute path to the file .
Read here
Where is the android data folder exists ?since i have to save large files and users should not able to see them ,i think to use data folder.But i don't know where is located in android phone.does it is on sdcard or not ?
You should use Internal storage
Internal storage is best when you want to be sure that neither the user nor other apps can access your files.
Sample code:
File file = new File(context.getFilesDir(), filename);
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
public File getTempFile(Context context, String url) {
File file;
try {
String fileName = Uri.parse(url).getLastPathSegment();
file = File.createTempFile(fileName, null, context.getCacheDir());
catch (IOException e) {
// Error while creating file
}
return file;
}
For more details, please refer here.
Use the below to get the path of of data directory
File f = Environment.getDataDirectory();
System.out.println(f.getAbsolutePath());
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.
I'm a newbie Android developer. I have loaded an image using universal-image-loader and I would like to save it on my sd card. The file is created in the desired directory with the correct filename, but it always has a size of 0. What am I doing wrong?
A relevant snippet follows:
PS: The image already exists on disk, it's not being downloaded from the Internet.
private void saveImage(String imageUrls2, String de) {
String filepath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
File SDCardRoot = Environment.getExternalStorageDirectory()
.getAbsoluteFile();
String filename = de;
File myDir = new File(SDCardRoot+"/testdir");
Bitmap mSaveBit = imageLoader.getMemoryCache();
File imageFile = null;
try {
//create our directory if it does'nt exist
if (!myDir.exists())
myDir.mkdirs();
File file = new File(myDir, filename);
if (file.exists())
file.delete();
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
bos.flush();
bos.close();
} catch (IOException e) {
filepath = null;
e.printStackTrace();
Toast.makeText(getApplicationContext(),
R.string.diskful_error_message, Toast.LENGTH_LONG)
.show();
}
Log.i("filepath:", " " + filepath);
}
Yes, your code creates an file on sdcard_root/testdir/de only, and didn't write anything to it. Is "imageUrls2" the source image file? If yes, you can open that file with BufferedInputStream, read the data from BufferedInputStream, and copy them to output file with bos.write() before bos.flush() and bos.close().
Hope it helps.
save and upload a file from internal memory in android
I had try to save a file into internal memory
String smsXml = "<messages><sms><From>" + address + "</From><Date>" + finalDateString + "</Date><Body>" + msg +"</Body></sms></messages>";
try {
//saving the file as a xml
FileOutputStream fOut = openFileOutput("textMessage.xml",MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(smsXml);
osw.flush();
osw.close();
}
catch (Throwable e) {
Log.d("Exception","Exception:"+ e);
}
Now I try to upload the file to server But how can I get file path to upload this.I had successfully uploaded a .mp3 from sd card but how to do that from internal memory.Follow this link for uploading .mp3
final String uploadFilePath = "android/data/data/com.example.sms/files/";
final String uploadFileName = "textMessage.xml";
Use getFileStreamPath(). This will return the file created by openFileOutput method in Files directory.
File file = getFileStreamPath("textMessage.xml");
Then you can get the path String with getPath method:
String path = file.getPath();