guys i have a text file in my URL.On click of a button i am able to download it to sdcard.
But i need to replace the downloaded file with the file in raw folder.Both are different files.
this is how i am downloading from URL
File sdcard = Environment.getExternalStorageDirectory();
File dir = new File (sdcard.getAbsolutePath() + "/varun");
dir.mkdirs();
try {
u = new URL("http://hihowru.com/123.xml");
file = new File(dir,"123.xml");
startTime = System.currentTimeMillis();
Log.d("DownloadManager", "download begining");
Log.d("DownloadManager", "download url:" + url);
Log.d("DownloadManager", "downloaded file name:" + "a.mp3");
URLConnection uconnection = u.openConnection();
InputStream is = uconnection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos;
fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
Toast toast = Toast.makeText(getApplicationContext(), "Downloaded to Sdcard/varun"+audioxml, 0);
toast.show();
Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
Intent ii = new Intent(DownloadFiles.this,Relaxation.class);
startActivity(ii);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
but i need to replace this file(downloaded file) with the file in raw folder
download file name : hi.txt
raw folder name : hw.txt
how to acheive this please help
You can't modify or write a file in android resources or asset directory. Because of android apk file is read only. So you are able to only read it. Best way is copy that file in internal storage then use from that path, also after download file from url update that at internal storage path.
Update:
Code for copy file from /asset to application internal storage.
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
String newFileName = "/data/data/" + this.getPackageName() + "/" + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
Related
how to prevent storing same file selected in galary twice in internal storage in android .I tried with below code it copies same video many times in a folder in the internal storage .
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
new SaveVideoInFolder().execute(uri);
try {
InputStream is = getContentResolver().openInputStream(uri);
File storage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
File app_directory = new File(storage, "video_choosing");
if (!app_directory.exists())
app_directory.mkdirs();
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String filename = String.format("VID_%s.mp4", timestamp);
file = new File(app_directory, filename);
Toast.makeText(MainActivity.this,file.toString(),Toast.LENGTH_SHORT).show();
OutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[4096];
int read;
while ((read = is.read(buffer)) != -1)
output.write(buffer, 0, read);
output.flush();
output.close();
} catch (FileNotFoundException e) {
Log.e("TAG", "File Not Found", e);
} catch (IOException e) {
Log.e("TAG", "IOException", e);
}
}
// Create the storage directory if it does not exist
if (!file.exists()) {
if (!file.mkdirs()) {
/* Log.e(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");*/
return null;
}
only you have check that your file is exist bt if condition and make directory if it is not..
File file = new File(app_directory, filename);
if(file.exists()){
...
}
else {
...
}
I am going with the download of files from the browser and stored in the internal storage of my device and the path appears as like /data/data/com.example/files/downloads/sample.pdf
but on next day i get the file path as empty ""
using below code to save the file from browser:
private String downloadfile(Uri uri) {
int count;
String fileName = "";
try {
// Output stream to write file
String root = null;
// if (Environment.isExternalStorageRemovable())
// else
root = getFilesDir().toString()+ "/download/";
File file = new File(root);
if (!file.exists())
file.mkdirs();
fileName = file.getAbsolutePath();
file = new File("" + uri);
fileName = fileName + "/" + file.getName();
URL url = new URL(uri.toString());
URLConnection conection = url.openConnection();
conection.setRequestProperty("Content-Type",
"application/octet-stream");
conection.setRequestProperty("Expect", "100-continue");
conection.setRequestProperty("Content-Disposition", "attachment");
conection.setRequestProperty("filename", file.getName());
conection.connect();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream(fileName);
file = new File(fileName);
file.createNewFile();
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
String inputs = "EX";
Parameter.trackApplication(inputs, e.getMessage());
e.printStackTrace();
}
return fileName;
}
How can i solve this problem,please correct me where i am going wrong and help me out to fix this issue.
I tried writing a file to my android phone using phonegap ui.
I have given the write permission and i tried by using getExternalStorageDirectory() and by giving the absolute path. But still not able to write it.
s1 is the name of the file that i am writing in the external storage
Environment.getExternalStorageState();
//File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"/Android/");
File file = new File("/mnt/sdcard"+ File.separator + "Android" + File.separator);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Folder");
}
}
Environment.getExternalStorageState();
File outputFile = new File(file, s1);
FileOutputStream fileoutputstream = new FileOutputStream(outputFile);
byte abyte0[] = new byte[1024];
for (int i = 0; (i = inputstream.read(abyte0)) > 0;)
fileoutputstream.write(abyte0, 0, i);
fileoutputstream.close();
inputstream.close();
I wrote a quick working demo of writing a file to the external storage.
If this still doesn't work maybe it is a phonegap specific issue.
Hope this helps:
InputStream is = null;
OutputStream os = null;
byte[] buffer = new byte[2048];
int bytes_read = 0;
File inputFile = new File("/init.rc");
File outputFile = new File(Environment.getExternalStorageDirectory() + "/testfile");
try
{
is = new FileInputStream(inputFile);
os = new FileOutputStream(outputFile);
while ((bytes_read = is.read(buffer)) != -1)
{
os.write(buffer, 0, bytes_read);
}
}
catch (Exception ignore) {}
finally
{
try
{
is.close();
}
catch (Exception ignore) {}
try
{
os.close();
}
catch (Exception ignore) {}
}
if (outputFile.exists())
{
Toast.makeText(this, "Success!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this, "Failure!", Toast.LENGTH_LONG).show();
}
I have a jar file for which i need to pass file object. How can i pass resource or assets to that method as a file object?
How to convert assets or raw files in the project folders in to file objects ?
Here is what I did:
Copy Your asset file into SDCard:
AssetManager assetManager = context.getResources().getAssets();
String[] files = null;
try {
files = assetManager.list("ringtone"); //ringtone is folder name
} catch (Exception e) {
Log.e(LOG_TAG, "ERROR: " + e.toString());
}
for (int i = 0; i < files.length; i++) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("ringtone/" + files[i]);
out = new FileOutputStream(basepath + "/ringtone/" + files[i]);
byte[] buffer = new byte[65536 * 2];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
Log.d(LOG_TAG, "Ringtone File Copied in SD Card");
} catch (Exception e) {
Log.e(LOG_TAG, "ERROR: " + e.toString());
}
}
Then read your file by the path:
File ringFile = new File(Environment.getExternalStorageDirectory().toString() + "/ringtone", "fileName.mp3");
There you go. You have a copy of file object of your asset file. Hope this helps.
I'm not aware of any way to get an actual File object, but if you can work with a FileDescriptor, you could do:
FileDescriptor fd = getAssets().openFd(assetFileName).getFileDescriptor();
How Do I Copy songs or image to my SD Card. i.e download image and save to sd card in android.
Thanks , shiv
Try this code:
File src = new File(Your_current_file);
File dest = new File(destination_place);
public void copyFile(File src, File dest) throws IOException
{
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}
in.close();
out.close();
}
Make sure to Give the permission for External Storage if you need:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Hope this will helps you.
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdcard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "filename");
FileOutputStream f = new FileOutputStream(file);
Dont forget to add permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
private final String PATH = "/data/data/com.whatever.whatever/"; //put the downloaded file here
public void DownloadFromUrl(String imageURL, String fileName) { //this is the downloader method
try {
URL url = new URL("http://yoursite.com/" + imageURL); //you can write here any link
File file = new File(fileName);
long startTime = System.currentTimeMillis();
Log.d("ImageManager", "download begining");
Log.d("ImageManager", "download url:" + url);
Log.d("ImageManager", "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
Log.d("ImageManager", "download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
And don't forget to add the following permissions:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = new File(path, "DemoPicture.jpg");
try {
// Make sure the Pictures directory exists.
path.mkdirs();
// Very simple code to copy a picture from the application's
// resource into the external file. Note that this code does
// no error checking, and assumes the picture is small (does not
// try to copy it in chunks). Note that if external storage is
// not currently mounted this will silently fail.
InputStream is = //Input stream of the file downloaded;
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}