I am trying to Copy file from internal memory card to external memory card
By googling i found this answer
try {
InputStream in = new FileInputStream("/storage/sdcard1/bluetooth/file7.zip"); // Memory card path
File myFile = new File("/storage/sdcard/"); //
OutputStream out = new FileOutputStream(myFile);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
session.showToast("file copied sucessfully");
} catch (FileNotFoundException e) {
showToast(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
showToast(e.getMessage());
e.printStackTrace();
}
its work for internal move to internal or external storage to external
but cross transferring do not work its throws an error Erofs read only file system
Try some thing like this:
new FileAsyncTask().execute(files);
and
// AsyncTask for Background Process
private class FileAsyncTask extends AsyncTask<ArrayList<String>, Void, Void> {
ArrayList<String> files;
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(ActivityName.this, "Your Title", "Loading...");
}
#Override
protected Void doInBackground(ArrayList<String>... params) {
files = params[0];
for (int i = 0; i < files.size(); i++) {
copyFileToSDCard(files.get(i));
} return null;
}
#Override
protected void onPostExecute(Void result) {
dialog.dismiss();
}
}
// Function to copy file to the SDCard
public void copyFileToSDCard(String fileFrom){
AssetManager is = this.getAssets();
InputStream fis;
try {
fis = is.open(fileFrom);
FileOutputStream fos;
if (!APP_FILE_PATH.exists()) {
APP_FILE_PATH.mkdirs();
}
fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory()+"/MyProject", fileFrom));
byte[] b = new byte[8];
int i;
while ((i = fis.read(b)) != -1) {
fos.write(b, 0, i);
}
fos.flush();
fos.close();
fis.close();
}
catch (IOException e1) {
e1.printStackTrace();
}
}
public static boolean copyFile(String from, String to) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(from);
if (oldfile.exists()) {
InputStream inStream = new FileInputStream(from);
FileOutputStream fs = new FileOutputStream(to);
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.close();
}
return true;
} catch (Exception e) {
return false;
}
}
Try this, Replace this line:
File myFile = new File("/storage/sdcard/");
with:
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File myFile = cw.getDir("imageDir", Context.MODE_PRIVATE);
Check this link, may be helpfull: click here
Related
I am generating pcap files and need to zip it. Currently i am able to generate and store the pcap file in local storage.
for zipping i am using below code:
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls) {
byte[] buffer = new byte[1024];
try {
zipFilePath = urls[0];
FileOutputStream fos = new FileOutputStream(zipFilePath + ".zip");
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze = new ZipEntry(urls[1]);
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream(zipFilePath);
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in.close();
zos.closeEntry();
//remember close it
zos.close();
return zipFilePath + ".zip";
} catch (IOException ex) {
ex.printStackTrace();
return "";
}
}
I am getting file not found exception at FileOutputStream fos = new FileOutputStream(zipFilePath + ".zip");
Here I am trying to upload multiple files on google drive app folder:
#Override
protected Boolean doInBackground(DriveFile...params) {
Drive.DriveApi.requestSync(mGoogleApiClient).await();
DriveFile file = params[0];
try {
DriveApi.DriveContentsResult driveContentsResult = file.open(
mGoogleApiClient, DriveFile.MODE_WRITE_ONLY, null).await();
if (!driveContentsResult.getStatus().isSuccess()) {
return false;
}
DriveContents driveContents = driveContentsResult.getDriveContents();
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(DbHelper.databasePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(driveContents.getOutputStream());
/*reading and writing data to and from file*/
int n = 0;
byte[] data = new byte[8 * 1024];
try {
while ((n = bufferedInputStream.read(data)) > 0) {
bufferedOutputStream.write(data, 0, n);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
com.google.android.gms.common.api.Status status =
driveContents.commit(mGoogleApiClient, null).await();
return status.getStatus().isSuccess();
}
return false;
}
While trying to upload two files the doInBackground method gets called only once and only one file gets uploaded which is last in an arraylist of files.
You need to post the complete code which is calling the doInBackground. The issue is with that part of code.
backupBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
createFolderOnGoogleDrive();
multipleFilesArrayList = listFilePath();
createFileAsyncTask = new CreateFileAsyncTask();
multipleFilestoAsynchTask = multipleFilesArrayList.get(i);
createFileAsyncTask.execute(multipleFilesArrayList);
}); }
I am using tesseract OCR in my app (Spl!t). When I launch the app from Eclipse to my phone, eng.traineddata is copied into /storage/emulated/0/Pictures/Receipts/tessdata/. But when I installed the app from the market, the eng.traineddata file is not copied into the folder. Is there something wrong with my code?
private File getOutputPhotoFile() {
directory = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"Receipts");
dataPath = directory.getAbsolutePath();
if (!directory.exists()) {
directory.mkdirs();
Toast.makeText(Trans_List.this, "Receipts Folder Created", Toast.LENGTH_SHORT).show();
File tessDir = new File(directory, "tessdata");
if (!tessDir.exists()) {
tessDir.mkdirs();
Toast.makeText(Trans_List.this, "Tessdata Folder Created", Toast.LENGTH_SHORT).show();
File trainingData = new File(tessDir, "eng.traineddata");
if(!trainingData.exists())
new CopyLibrary().execute(LANG);
}
}
String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss")
.format(new Date());
return new File(directory.getPath() + File.separator + "Receipt_"
+ timeStamp + ".jpg");
}
private class CopyLibrary extends AsyncTask<String, Void, Void> {
private void copyFile(InputStream in, OutputStream out)
throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
out.write(buffer, 0, read);
}
#Override
protected Void doInBackground(String... s) {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("Spl!t", "Failed to get asset file list.");
}
for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(dataPath + File.separator
+ "tessdata" + File.separator, LANG
+ ".traineddata");
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
Toast.makeText(Trans_List.this, "Tessdata copied", Toast.LENGTH_SHORT).show();
out = null;
} catch (IOException e) {
Log.e(TAG, "Failed to copy asset file");
}
}
return null;
}
}
I want to send 18 mb Data. It is working. But I have to wait too long that I get Email.
Code:
public void sendEmail()
{
emailSendReceiver = new EmailSendBroadcastReceiver();
EmailSend emailSend = new EmailSend();
emailSend.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public class EmailSend extends AsyncTask<Void, Void, Boolean>
{
#Override
protected Boolean doInBackground(Void... params)
{
boolean bResult = false;
String sDeviceID = configReader.getXmlValue(KEY_ID);
Mail m = new Mail("test#gmail.com", "testpass");
String[] toArr = {"toEmail#gmail.com"};
m.setTo(toArr);
m.setFrom("noreply#something.com");
m.setSubject("device number : "+sDeviceID );
m.setBody("device number : "+sDeviceID);
try
{
String sTxtFileName = sDeviceID+"_"+".txt";
String sFileUrl = Environment.getExternalStorageDirectory().getAbsolutePath()+"/data_source/"+sTxtFileName;
m.addAttachment(sFileUrl);
if(m.send())
{
bResult = true;
}
else
{
// something
}
}
#Override
protected void onPostExecute(Boolean result)
{
super.onPostExecute(result);
if(result == true)
{
// something
}
}
}
}
The Question is. How can I make it faster? I have 6 AsyncTask. And I don't like to make it with activity.
As suggested by all It would be handy to zip or gzip the file. The same is available in
java.util.zip*
package. Furthermore you could find help for the same here
public void makeZip(String sFile, String zipFileName)
{
FileOutputStream dest = null;
ZipOutputStream out;
byte data[];
FileInputStream fi = null;
int count;
try
{
dest = new FileOutputStream(zipFileName);
out = new ZipOutputStream(new BufferedOutputStream(dest));
data = new byte[BUFFER];
fi = new FileInputStream(sFile);
BufferedInputStream origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(sFile);
out.putNextEntry(entry);
while((count = origin.read(data, 0, BUFFER)) != -1)
{
out.write(data, 0, count);
}
origin.close();
out.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
I'm trying to download a file using an AsyncTask on Android. I want to display a ProgressDialog which should have a progress bar to show the status of the download. I'm using the onProgressUpdate() function for that and implemented a call to publishProgress() in my doInBackground() function. However, the progress dialog only pops up after downloading the file. My code:
protected Long doInBackground(URL...urls) {
for (int i = 0; i < urls.length; i++) {
url = urls[i];
try {
URLConnection conn = url.openConnection();
conn.connect();
totalSize = conn.getContentLength();
BufferedInputStream bis = new BufferedInputStream(url.openStream());
FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/forvo_temp.mp3");
BufferedOutputStream bos = new BufferedOutputStream(fos,1024);
byte [] data = new byte[1024];
int x=0; int c=0;
while((x=bis.read(data,0,1024))>=0){
bos.write(data,0,x);
c += 1024;
publishProgress(c);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return 0L; // Don't know what to do with this
}
protected void onProgressUpdate(Integer...args) {
pd = ProgressDialog.show(context, "Downloading...", "Downloading...", true, false);
pd.setProgress(args[0] / totalSize);
}
I guess the whole file is downloaded when I call new BufferedInputStream(url.openStream()). How can I monitor the download progress?
Wrap URL input stream with you own InputStream that just reads bytes and "monitors" the status, e.g. sends notifications.
It is simple: InputStream is an abstract class with only one abstract method:
public abstract int read() throws IOException;
In your case it should read bytes from stream that it wraps.
public class NotifcationInputStream extends InputStream {
private InputStream in;
private int count;
private Collection<ByteListener> listeners = new ArrayList<ByteListener>();
NotificationInputStream(InputStream in) {
this.in = in;
}
public int read() throws IOException {
int b = in.read();
byteReceived(b);
return b;
}
public void addListener(ByteListener listener) {
listeners.add(listener);
}
private void byteReceived(int b) {
for (ByteListener l : listeners) {
l.byteReceived(b, ++count);
}
}
}
public interface ByteListener extends EventListener {
public void byteReceived(int b, int count);
}
The problem here is how to show the process bar: you have to know total number of bytes. You can get it from HTTP header content-length if your resource is static. Otherwise you need appropriate server support or heuristics.
This code is useful showing download items totol size and downloaded size.
private static final int DOWNLOAD_ONPROGRESS = 1;
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DOWNLOAD_ONPROGRESS:
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Downloading latest ...");
progressDialog.setCancelable(true);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
try {
progressDialog.show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return progressDialog;
default:
return null;
}
}
You can use AsyncTask for downloading the version in background.
private class DownLoad extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
logger.info("LoadDataAsync onPreExecute");
showDialog(DOWNLOAD_ONPROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count = 0;
try {
URL url = new URL(aurl[0]);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
int contentlength = urlConnection.getContentLength();
progressDialog.setMax(contentlength);
String PATH = "";
File file = null;
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
PATH = Environment.getExternalStorageDirectory()
+ "/download/";
file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "telfaz.apk");
OutputStream fos = new FileOutputStream(outputFile);
InputStream is = new BufferedInputStream(url.openStream());
byte[] buffer = new byte[1024];
long len1 = 0;
while ((count = is.read(buffer)) != -1
&& !downLoad.isCancelled()) {
len1 += count;
publishProgress("" + len1);
fos.write(buffer, 0, count);
}
fos.flush();
fos.close();
is.close();
}
logger.info("Success -> file downloaded succesfully. returning 'success' code");
return Util.APK_DOWNLOAD_SUCCESS;
} catch (IOException e) {
logger.error("Exception in update process : "
+ Util.getStackTrace(e));
}
logger.info("Failed -> file download failed. returning 'error' code");
return Util.APK_DOWNLOAD_FAILED;
}
#Override
protected void onPostExecute(String result) {
logger.info("on DownLoad onPostExecute. result : " + result);
progressDialog.dismiss();
removeDialog(DOWNLOAD_ONPROGRESS);
if (result.equalsIgnoreCase(Util.APK_DOWNLOAD_SUCCESS)) {
Update();
} else {
Toast.makeText(DownloadAllContentsActivity.this,
getString(R.string.updateApplicationFailed),
Toast.LENGTH_LONG).show();
loadDataAsync.execute();
}
}
#Override
protected void onProgressUpdate(String... values) {
if (values != null && values.length > 0) {
progressDialog.setProgress(Integer.parseInt(values[0]));
}
}
}