Editing existing file in Android - java

I am trying to edit existing file on the device by-First- select the file using selector that retrieve the path of the file like this "mnt/sdcard/file.png". Then I pass it to reader to read the existing file then modify it by by shifting the Ascii of every char. Then Overwrite it again to replace the old one.
I have tested the code on a desktop app on PC files and it Works perfect, but does not work as an Android app. It worked on my device once but did not work again
About what I did:
1)Add writing on External source Permission in the Mainafest file
2)Select the file right and retrieve it path
3)Read the file content true
File file = f;
FileInputStream fin;
fin = new FileInputStream(file);
byte fileContent[] = new byte[(int)file.length()];
fin.read(fileContent);
4)Modify the file bytes
5)Write back (Overwrite) in the original file
FileOutputStream fos = new FileOutputStream(f.getAbsolutePath());
fos.write(enc_msg);
fos.write((byte)seed);
fin.close();
fos.close();
6)Set the file to null again
7)Call finish() in the onClickListner
Thanks in Advance

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
However, the device must be disconnected from USB. Otherwise you need to unplug and replug the device to see the changes.

After a lot of work, I have reached the final solution by:
1)Using Common-io library
http://commons.apache.org/proper/commons-io/download_io.cgi
2)Writing this simple line only after import common-io
FileUtils.writeByteArrayToFile(new File(file.getAbsolutePath()), myByteArray, false);
the last attribute (Fasle) for overriding the file .. Append flag

Related

Writing files to external storage in Android failing

As the title points out, I'm having trouble writing files to the external storage. My debug device is a Nexus 5. The thing is, I'm able to read files perfectly from the device (I've been trying with the ones in the Download Folder) but cannot write them. I am aware that I must do this while the device isn't connected to the computer. But it doesn't work either.
In fact, I've tried reading the state of the SD card prior to writing to it (which didn't work, of course). The state showed as "mounted" either when the device was connected to my PC or not. And I compared the state to Environment.MEDIA_MOUNTED_READ_ONLY and Environment.MEDIA_MOUNTED without any success. My device is in none of these states.
One thing which you must know is that my phone doesn't have an external SD card, as it's an internal one. This results in my device having a "/storage/emulated/0/..." directory for the external storage.
I must also point out that I have implemented the following tags in my Android Manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="ANDROID.PERMISSION.WRITE_EXTERNAL_STORAGE"/>
I don't have any clue to what might be happening. Another thing which might help is that I've tried managing files with winrar (for Android) and I've been able to remove files with the device connected to my PC as well as without having it connected. So I don't know what to do.
The code which I'm using to write a file is the following. Bear in mind that it should read an image file (which it does), convert it into a string, convert it back into an image and then save it to the Downloads Folder:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/base_image.jpg");
// Reading a Image file from file system
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
// Converting Image byte array into Base64 String
String imageDataString = encodeImage(imageData);
// Converting a Base64 String into Image byte array
byte[] imageByteArray = decodeImage(imageDataString);
File newFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "converted_image.jpg");
//Write a image byte array into file system
FileOutputStream imageOutFile = new FileOutputStream(newFile);
imageOutFile.write(imageByteArray);
imageInFile.close();
imageOutFile.close();
What should I do?
Just fix ANDROID.PERMISSION.WRITE_EXTERNAL_STORAGE to android.permission.WRITE_EXTERNAL_STORAGE in your uses-permission.
I've encounterd this problem, UPPERCASE in permission is not useful.
FileOutputStream does NOT automatically create a file if it's not exist.
So, you need to check and create if your file doesn't exist.
if(!newFile.exists()) {
newFile.createNewFile();
}
Hope this help!

smb file writing in local drive from network drive is not working

I am trying to write a file in my local drive which is available in a network drive on a server. I can write this image and I can see even the size of the file available. But, when I'm opening the file it says preview not available. Content of the file is not coming.
Code which I read the network file
SmbFileInputStream sfis = null;
sfis = new SmbFileInputStream(serverFile);
fileBytes = new byte[(int) serverFile.length()];
sfis.read(fileBytes);
Code which I write the file in my local drive
FileOutputStream fos;
fos = new FileOutputStream(tempFile);
fos.write(fileBytes);
I also tried with file.copyTo method by giving my local file like a smbfile.
serverFile.copyTo(ss);
I figured it out and it works fine.
Change first two lines to
InputStream sfis = new SmbFileInputStream(serverFile);
real change is reference of the variable is now
InputStream

Throw a file to the user

I'm using data handling
FileOutputStream fileOutputStream = new FileOutputStream(file_name);
workBook.write(fileOutputStream);
fileOutputStream.close();
After the code runs the file is saved somewhere in the system without any indication. I want that the file should be available to user as a pop up when we download anything of the internet and the user can save the file wherever they want.
You have to get outputstream from response and write whole file in that stream. refer to example for more detail

What is my directory when writing files in Android?

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_WORLD_READABLE);
fos.write(string.getBytes());
fos.close();
When trying to delete one of those files, this is what I use, but it's returning false.
String tag = v.getTag().toString();
File file = new File(System.getProperty("user.dir")+"/"+tag);
String s = new Boolean (file.exists()).toString();
Toast.makeText(getApplicationContext(), s, 1500).show();
file.delete();
How can I overcome this problem?
Use getFileStreamPath(FILENAME) to find your file. From the docs:
Returns the absolute path on the filesystem where a file created with openFileOutput(String, int) is stored.
Your current working directory.
To help diagnose the problem, use file.getAbsolutePath() to see the full path.
It could also be a permissions problem, if you're trying to delete from another application. If so, you may need to change to MODE_WORLD_WRITEABLE (insecure), or restructure your code so the create and delete are called by the same app.
EDIT: That was mostly incorrect. I didn't realize that openFileOutput didn't use the current working directory.
Use same contents as 'FILENAME' variable in your first snippet in the second snippet while trying to delete.
String RootDir = Environment.getExternalStorageDirectory()
+ File.separator + "Video";
File RootFile = new File(RootDir);
RootFile.mkdir();
FileOutputStream f = new FileOutputStream(new File(RootFile, "Sample.mp4"));
i used this code to save the video files to non-default location. Hope this will be useful to you.By default it is storing in sd card
For each application the Android system creates a "data/data/package of the application" directory.
Files are saved in the "files" folder under this directory
to change the default directory the above code will be used
the default working directory can be displayed using fileobject.getAbsolutePath()

Returning an Input Stream from Parcel File Descriptor using Androids DownloadManager

I'm trying to download a file using the android DownloadManager, access the file, and write it to a new location (in this example I'm downloading a database which is compiled server side and needs to be wrote to the /database/ directory).
I've been reading up and managed to download the file, and activate the BroadcastReceiver, but at this point I get stuck.
I've returned the ParcelFileDecriptor file but I'm having trouble converting it to a stream in any way. I can't decide if the ParcelFileDecriptor.AutoCloseInputStream is a red herring or not, but I'm pretty sure the ParcelFileDecriptor has relativity to a stream, but I'm really struggling to work it out. Any help would be much appreciated.
Assuming you've started the download already and set up the Broadcast Reciver, the following code will do the job...
ParcelFileDescriptor file = dMgr.openDownloadedFile(downloadId);
File dbFile = getDatabasePath(Roads.DATABASE_NAME);
InputStream fileStream = new FileInputStream(file.getFileDescriptor());
OutputStream newDatabase = new FileOutputStream(dbFile);
byte[] buffer = new byte[1024];
int length;
while((length = fileStream.read(buffer)) > 0)
{
newDatabase.write(buffer, 0, length);
}
newDatabase.flush();
fileStream.close();
newDatabase.close();
If you're looking for more information on overwriting a database with your own check this link (Also where most of the above info has come from):
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

Categories