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();
Related
I'm developing an app which stores few setting in two .xml files, saved on internal storage. I need to save them in there, so please don't answer me "Save them on SD-cards".
I try to uninstall an then re-install (from Android Studio) my app to see if the android:allowBackup="true" works also for internal stored file but the answer was no.
Is this because I done the re-install from the IDE or I need to add some code somewhere?
Thanks for help.
Starting API level 29 there is the "hasFragileUserData" manifest flag
The documentation states that
If true the user is prompted to keep the app's data on uninstall.
May be a boolean value, such as "true" or "false".
Sample code:
<application
....
android:hasFragileUserData="true">
You can save those file using Environment.getExternalStorageDirectory() This stores on the external storage device. Dont get confused with the term external storage as the SD card. SD card is the secondary external storage. But Environment.getExternalStorageDirectory() returns top-level directory of the primary external storage of your device which is basically a non removable storage.
So the file path can be /storage/emulated/0/YOURFOLDER/my.xml
So even if you uninstall the app, these files will not get deleted.
You can use this snippet to create a file in your primary external storage:
private final String fileName = "note.txt";
private void writeFile() {
File extStore = Environment.getExternalStorageDirectory();
// ==> /storage/emulated/0/note.txt
String path = extStore.getAbsolutePath() + "/" + fileName;
Log.i("ExternalStorageDemo", "Save to: " + path);
String data = editText.getText().toString();
try {
File myFile = new File(path);
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.close();
Toast.makeText(getApplicationContext(), fileName + " saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
Don't forget to add below permission in Android Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
You can then read that file as below:
private void readFile() {
File extStore = Environment.getExternalStorageDirectory();
// ==> /storage/emulated/0/note.txt
String path = extStore.getAbsolutePath() + "/" + fileName;
Log.i("ExternalStorageDemo", "Read file: " + path);
String s = "";
String fileContent = "";
try {
File myFile = new File(path);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((s = myReader.readLine()) != null) {
fileContent += s + "\n";
}
myReader.close();
this.textView.setText(fileContent);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), fileContent, Toast.LENGTH_LONG).show();
}
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().
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'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.
I would like to upload a string as a text file to skydrive from my android application. Is this possible?
Thanks.
Yes it is possible, you have to create a file from the user Entered String, and then save this .txt file on your Server(skydrive)
Its the code which will create a file from the string.
private String filename = "MySampleFile.txt";
private String filepath = "MyFileStorage";
File myInternalFile;
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
myInternalFile = new File(directory , filename);
FileOutputStream fos = new FileOutputStream(myInternalFile);
fos.write(myInputText.getText().toString().getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}finally{
Toast.makeText(context, MySampleFile.txt saved to Internal Storage...", 1000).show;
}
Now save this file in skydrive using skydrive api.