I'm trying to display the path of the file by calling getAbsolutePath(), but the Application
displays nothing.
Java Code:
public void createExternalStorageDirectory() {
File file = new File(getExternalFilesDir(null), fileName);
try {
InputStream is = getResources().openRawResource(R.drawable.ic_launcher);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
Toast.makeText(getBaseContext(), file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
is.close();
os.close();
} catch (IOException e) {
Log.w("ExternalStorage", " Error writing " + file, e);
}
}
Add the External File permission to the manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And try using getApplicationContext() intead of getBaseContext()
you can try to use Environment.getExternalStorageDirectory() instead of getExternalFilesDir(null)
Related
I am a beginner when it comes to Android. I encountered a problem, regarding writing to a file. I want to save to a file the input I get in a form. However, the piece of code that I wrote is not writing in my file. Could anyone please help me?
The code looks like that:
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuilder s = new StringBuilder();
s.append("Event name: " + editText1.getText() + "|");
s.append("Date: " + editText2.getText() + "|");
s.append("Details: " + editText3.getText() + "|");
File file = new File("D:\\config.txt");
try {
BufferedWriter out = new BufferedWriter(new FileWriter(file, true), 1024);
out.write(s.toString());
out.newLine();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
So, I have a form containing 3 fields: the name of an event, the date and the description. These I want to save to my file. I should mention that I use an emulator for testing.
Use following path for file. It will write file to your root folder of storage.
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file= new File(extStorageDirectory, "config.txt");
writeToFile("File content".getBytes(), file);
writeToFile
public static void writeToFile(byte[] data, File file) throws IOException {
BufferedOutputStream bos = null;
try {
FileOutputStream fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(data);
}
finally {
if (bos != null) {
try {
bos.flush ();
bos.close ();
}
catch (Exception e) {
}
}
}
}
Don't forget to add following permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
https://github.com/rznazn/GPS-Data-Logger/blob/master/app/src/main/java/com/example/android/gpsdatalogger/StorageManager.java
Here is a... nearly complete class for writing to the documents folder on the emulated external storage of the device.
Don't forget to add the write permissions to manifest.
I need to write a simple text in a file "test.txt".
This is my code:
String SDCARD = Environment.getExternalStorageDirectory().getAbsolutePath();
String FILENAME = "test.txt";
File outfile = new File(SDCARD+File.separator+FILENAME);
if (outfile.exists()) { Log.d("Filename","the file exists"); }
Log.d("Filename",SDCARD+File.separator+FILENAME);
FileOutputStream fos = new FileOutputStream(outfile,true);
fos.write("just a test".getBytes());
fos.close();
In the manifest there is the permission request:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xrobot.john.texttest">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
and the targetsdkversion is 15.
Logcat display this:
12-01 12:57:26.178 29663-29663/com.xrobot.john.softkeyboard D/Filename﹕ the file exists
12-01 12:57:26.178 29663-29663/com.xrobot.john.softkeyboard D/Filename﹕ /storage/emulated/0/test.txt
and the file text.txt is always empty.
Why ?
You are perhaps missing permission for reading that file.
Also, you are missing fos.flush() between fos.write() and fos.close() , that can easily cause that unexpected behavior.
Use a buffered writer to write your string to a file
BufferedWriter writer = null;
try
{
writer = new BufferedWriter( new FileWriter(SDCARD+File.separator+FILENAME));
writer.write( "just a test");
}
catch ( IOException e)
{
}
finally
{
try
{
if ( writer != null)
writer.close( );
}
catch ( IOException e)
{
}
}
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 try to write text in file.i wrote code ,witch can to write text ,but if i will use again my code again text is rewrite in file.for example if i first time write "Hello android" and then "Sir",result is only "Sir".i want "Hello android Sir"
your_file = new File("/sdcard/facebookUser");
try {
Writer writer = new OutputStreamWriter(new FileOutputStream(
your_file), "UTF-8");
writer.write(facebook_user_name + ",");
writer.write(facebook_id);
writer.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
how i can write code to save another text in this file second time?
new FileOutputStream(your_file, true)
public FileOutputStream(String name, boolean append) throws FileNotFoundException
append - if true, then bytes will be written to the end of the file rather than the beginning
Instead of:
writer = new OutputStreamWriter(new FileOutputStream(
your_file), "UTF-8");
Use:
writer = new OutputStreamWriter(new FileOutputStream(
your_file, true), "UTF-8");
This sets the FileOutputStream in append mode.
java.io.FileOutputStream.FileOutputStream(File file, boolean append)
throws FileNotFoundException
Constructs a new FileOutputStream that writes to file. If append is
true and the file already exists, it will be appended to; otherwise it
will be truncated. The file will be created if it does not exist.
try {
int n = 0;
String Name = "file";
File myFile = new File("/sdcard/test/");
if (!myFile.exists()) {
boolean b = myFile.mkdirs(); }
myFile = new File("/sdcard/test/"+Name+".txt");
while (myFile.exists())
{
myFile = new File("/sdcard/test/"+Name+n+".txt");
n++;
}
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
String str = "Your text to write";
myOutWriter.append(str);
myOutWriter.close();
fOut.close();
} catch (Exception e) {}
And do not forget permision:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Vladimir Kulyk and user2450263 are correct! You have to write a file in append mode. try this link.
I have a set of image urls. I download it to bitmap. Now I want to store these images into sdcard/project folder. If I don't have such a file, I have to create it. What I have done right now is:
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
File file = new File(path, imageName);
if(!file.exists()) {
file.mkdir();
try {
fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(), "file://"
+ file.getAbsolutePath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
But I am not getting images inserted into sdcard. What is wrong in my code? Please reply. Thanks in advance.
Try using the below code:
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
String fileName = edtNameImage.getText().toString().trim();//this can be changed
if (fileName.equalsIgnoreCase("")) {
Toast.makeText(context, "Fields cannot be left blank",
Toast.LENGTH_SHORT).show();
return false;
}
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + fileName);
// write the bytes in file
FileOutputStream fo;
try {
file.createNewFile();
fo = new FileOutputStream(file);//snapshot image is the image to be stored.
if (snapShotImage!=null)
{
snapShotImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
}else{
return false;
}
fo.write(bytes.toByteArray());
// ChartConstants.IMAGE_STORAGE++;
fo.flush();
fo.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return true;
You can also check for duplicacy in names with some additional code lines.
Let me know if it helps.
Have you made sure that the appropriate permissions for writing to/reading from an external storage device have been set in your Manifest.xml file?
Also, does the code exit with any of the exceptions above? Print more illustrative messages than the stacktrace. Something like so:
try {
} catch (FileNotFoundException e) {
Log.v(this.toString(), "Exception caught in block");
}
or something on these lines..
HTH
Sriram
Problems with your code:
1) You are creating a directory with the filename. Instead try mkdir() with only the 'path'
2) Pass only 'file.getAbsolutePath()' without the "file://" to insertImage() function
3) There is an alternate api to insertImage for which you need not create one more file locally. Pass the bitmap directly to that.
Hope this helps.