Error writing to SD Card - android

Please help...
I have created a text file in the first Activity of my App, which is all working fine.
In My next Activity, i want to append to the text file.
But when i try to append the catch throws up the following error..
mnt/scard/PatRecords/testfile.txt contains a file seperator
And nothing is added to the file.
my code for appending is..
try {
File directory = new File
(Environment.getExternalStorageDirectory().getPath()+"/PatRecords");
FileOutputStream fOut = openFileOutput(directory.getPath()+"/"+FileName$, MODE_APPEND);
OutputStreamWriter OutWriter = new OutputStreamWriter(fOut);
OutWriter.write(TestNo$+"\n");
OutWriter.write(Date$+"\n");
OutWriter.close();
fOut.close();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
Error=1;
}//End of try/catch
I have tried removing the seperators etc but still doesn't work, and as far as i can see
the path shown in the catch error is correct...?

openFileOutput() is for opening files in your program data folder, which is located on the internal memory, you may only supply the file name, not the path, hence the complain mnt/scard/PatRecords/testfile.txt contains a file separator.
if you want to open files on the SD card, you have to use FileOutputStream() or something like that:
File of = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream fos = new FileOutputStream(file);
fos.write(data);
fos.flush();
fos.close();

Related

creating a txt file on sd card but i cant find it

I want to create a textfile on my sdcard. I found lots of codesamples and tried them. None of them responded any Exception so i expected them to work, but when I was exploring my sdcard, I could not find a textfile.
Here is the attempt I am trying:
try {
File sdcard = Environment.getExternalStorageDirectory();
File myFile = new File(sdcard,"text.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(encodedString); // this is a long string
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"written to: "+myFile.getAbsolutePath(),
Toast.LENGTH_SHORT).show();
Here is what the Toast is telling me:
What I expect: "written to: /sdcard/text.txt"
What I get: "written to: /storage/emulated/0/text.txt"
Why is the app not saving the textfile as intended onto the sdcard and what do I have to change in order to make it do it?
getExternalStorageDirectory() does not necessary return /sdcard directory. See here Environment.getExternalStorageDirectory does not return the path to the removable storage

Issue on appending a file in android

I am creating an android application which reads and writes data to a file in the location /sdcard/ReadandWrite/.when i writing to that file it does not write in append mode.it will removes the old data and writes the new one.please help me to solve this.Here is my code.
private File openfile() {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/ReadandWrite");
dir.mkdirs();
File file = new File(dir, "myfile.txt");
file.setWritable(true);
if(file.exists())
{
file.canRead();
file.setWritable(true);
}
else {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
private void writetofile() {
try {
File file=openfile();
OutputStreamWriter myOutWriter =
new OutputStreamWriter(new FileOutputStream(file));
myOutWriter.append(text.getText());
myOutWriter.close();
myOutWriter.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();
}
You need to configure the FileOutputStream to use append mode. From JDK documentation:
public FileOutputStream(String name,
boolean append)
throws FileNotFoundException
Creates a file output stream to write to the file with the specified
name. If the second argument is true, then bytes will be written to
the end of the file rather than the beginning. A new FileDescriptor
object is created to represent this file connection.
First, if there is a security manager, its checkWrite method is called
with name as its argument.
If the file exists but is a directory rather than a regular file, does
not exist but cannot be created, or cannot be opened for any other
reason then a FileNotFoundException is thrown.
Parameters:
name - the system-dependent file name
append - if true, then bytes will be written to the end of the file rather than the beginning Throws:
FileNotFoundException - if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or
cannot be opened for any other reason.
SecurityException - if a security manager exists and its checkWrite method denies write access to the file. Since:
JDK1.1 See Also:
SecurityManager.checkWrite(java.lang.String)
So change
OutputStreamWriter myOutWriter = new OutputStreamWriter(new FileOutputStream(file));
to
OutputStreamWriter myOutWriter = new OutputStreamWriter(new FileOutputStream(file, true));

What directory will FileOutputStream save my simple file in(Android)? How do I find out if it has saved?

I'm trying to recreate a simple text editing Android app and so far I have this code to save the file:
String filename = "myfile";
String content = edit.getText().toString();
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename,
Context.MODE_PRIVATE);
outputStream.write(content.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
However I have no idea where in the internal storage this is being saved. How can I access/look at this directory to confirm the file has actually saved. I cant seem to find the file in File explorer in Eclipse (Heck, I can't even find the app name).Also, how would I go about loading this file once it is located? Thanks.
openFileOutput(filename,
Context.MODE_PRIVATE); is application private directory output stream api. Your file will saved in your /data/data/your_packagename directory.

File upload picture android

I develop application with imageview, my problem is when I clicked button load picture, then will be shown gallery, then I want to copy selected image to res/drawable android, is it possible? if yes, can give me source code ?
Regards,
You cannot write to res/drawable. You can download image which can be stored in sdcard but you can't add images dynamically to drawable folder.
i am afraid res/ is read-only while running. Instead they give us the option or create files and our personal data in our application space
=====
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/app_name");
dir.mkdirs();
File file = new File(dir, "myAppData.jpg");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println(bytes);// bytes would be data from the source file
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
//..
} catch (IOException e) {
//...
}

Saved Bitmap doesn't appear on SD Card

I am working on an app in which I would like to save some Bitmaps to the SD Card. I have looked at a lot of examples and other questions, and from that I have made the following code:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
String dirPath = Environment.getExternalStorageDirectory().toString() + "/myFolder";
File dir = new File(dirPath);
dir.mkdirs();
String fileName = "bitmapname.jpg";
File file = new File(dirPath, fileName);
FileOutputStream fileOutPutStream;
try {
boolean created = file.createNewFile();
Log.d("Checks", "File created: " + created);
fileOutPutStream = new FileOutputStream(file);
fileOutPutStream.write(byteArrayOutputStream.toByteArray());
fileOutPutStream.close();
} catch (FileNotFoundException e) {
Log.d("Checks", "FileNotFoundException");
e.printStackTrace();
} catch (IOException e) {
Log.d("Checks", "IOException");
Log.d("Checks", e.getMessage());
e.printStackTrace();
}
I don't see what's wrong with this code. It doesn't give any errors and my app runs without crashing. However, when I connect my phone to my computer and open the SD Card I do not see the folder "myFolder" and I can not find the saved image anywhere. Do you guys have any ideas as to why this is?
EDIT: I noticed that I can see the saved bitmaps in the Android gallery, and they are indeed in a folder called "myFolder". However, I still don't see them when I connect my phone to my computer and browse my sd card.
From my experience I had similar issued when I forgot the fileOutPutStream.flush(); before the close().
Are you sure you are setting the permission to write to SD card? Try setting this one:
WRITE_EXTERNAL_STORAGE
Edit:
Ok, try this:
Environment.getExternalStorageDirectory().getAbsolutePath()
Instead of:
Environment.getExternalStorageDirectory().toString()
Or even create a directory like this:
File dir = new File(Environment.getExternalStorageDirectory() +
File.separator +
"myFolder");
dir.mkdirs();

Categories

Resources