Zipping method generating infinite loop - android

I'm trying put all subfolders of a folder in a zip file, so I'm doing this:
public static void zipFolder(String inputFolderPath, String outZipPath) {
try {
FileOutputStream fos = new FileOutputStream(outZipPath);
ZipOutputStream zos = new ZipOutputStream(fos);
File srcFile = new File(inputFolderPath);
File[] files = srcFile.listFiles();
Log.d("", "Zip directory: " + srcFile.getName());
for (int i = 0; i < files.length; i++) {
Log.d("", "Adding file: " + files[i].getName());
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(files[i]);
zos.putNextEntry(new ZipEntry(files[i].getName()));
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
fis.close();
}
zos.close();
} catch (IOException ioe) {
Log.e("", ioe.getMessage());
}
I saw this code in this question
But, the code goes into loop because lenght is always 1024
The loop happens at the second file. I printed the fileList:
In this case I tried create the "aaaaaaa" file, the others are from another attempt and I didn't understand why they are showed, because the directory don't have none zip file.
PS: the directory that I'm trying compress has two subfolders. I don't know if this can influence.

I solved the problem :D
In my vision, the method don't consider subfolders, only files. In my case I have two folders inside files directory and the content inside them.
So, now I call the method for each subfolder and the outZipPath should be a public directory:
Controller.zipFolder(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath(), Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/content_" +
Util.formatoData.format(data).replace("/", ".") + ".zip");

Related

Download(copy?) a file from my res/raw folder to the default Android download location?

I am making a soundboard for practice and I want to give the user the ability to download the sound (that I have included in the app in the res/raw folder) onClick of a menu item but I can only find information about downloading from an internet url, not something that I already included in the apk.
What is the best way to do this? I would like to give them the option to save to an SD card also if this is possible. A point towards the correct class to use in the documentation would be great! I've been googling to no avail.
Thanks!
Try something like this:
public void saveResourceToFile() {
InputStream in = null;
FileOutputStream fout = null;
try {
in = getResources().openRawResource(R.raw.test);
String downloadsDirectoryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
String filename = "myfile.mp3"
fout = new FileOutputStream(new File(downloadsDirectoryPath + filename));
final byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} finally {
if (in != null) {
in.close();
}
if (fout != null) {
fout.close();
}
}
}
I don't know about the raw but I did a similar thing in my app using the assets folder. My files are under the assets/backgrounds folder as you can probably guess from the code below.
You can modify this code and make it work for you (I know I will only have 4 files which is why I have i go from 0 to 4 but you can change this to whatever you want).
This code copies the file starting with prefix_ (like prefix_1.png, prefix_2.png, etc) to my cache directory but you can obviously change the extension, the filename or the path you would like to save the assets to.
public static void copyAssets(final Context context, final String prefix) {
for (Integer i = 0; i < 4; i++) {
String filename = prefix + "_" + i.toString() + ".png";
File f = new File(context.getCacheDir() + "/" + filename);
if (f.exists()) {
f.delete();
}
if (!f.exists())
try {
InputStream is = context.getAssets().open("backgrounds/" + filename);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
fos.close();
} catch (Exception e) {
Log.e("Exception occurred while trying to load file from assets.", e.getMessage());
}
}
}

move video file from /mnt/sdcard to /mnt/extsd

I am trying to move file from /mnt/sdcard to /mnt/extsd
Currently file is stored in /mnt/sdcard/DCIM/camera after shooting a video
but now i want to move this file to /mnt/extsd
I am using following code
File fromFile=new File( "/mnt/sdcard/folderpath" ,"/video.mp4");
File toFile=new File("/mnt/extsd" ,fromFile.getName());
fromFile.renameTo(toFile);
I read that renameTo dosen't work for moving in different file systems
Please help me
 try {
  java.io.FileInputStream fosfrom = new java.io.FileInputStream(fromFile);
  java.io.FileOutputStream fosto = new FileOutputStream(toFile);
  byte bt[] = new byte[1024];
  int c;
  while ((c = fosfrom.read(bt)) > 0) {
  fosto.write(bt, 0, c); //将内容写到新文件当中
  }
  fosfrom.close();
  fosto.close();
  } catch (Exception ex) {
  Log.e("readfile", ex.getMessage());
  }
  }
give source file where exist ur file and target location where u want to store .
public static void copyDirectoryOneLocationToAnotherLocation(File sourceLocation, File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdir();
}
String[] children = sourceLocation.list();
for (int i = 0; i < sourceLocation.listFiles().length; i++) {
copyDirectoryOneLocationToAnotherLocation(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]));
}
} else {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// 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();
}
}
according to Android docs "Both paths must be on the same mount point" like it could be used for file renaming only in case of different paths. So if you want to move it you probably should copy it and then rename and then delete the source file. But in this case you are trying not only to move the file from one FS to another but also you are trying to use /mnt/extsd which might not be able at all. Follow this question about such paths.

Tesseract OCR Android tessdata directory not found

I'm currently developing an Android app using OCR and I've reached the point where I'm calling the BaseAPI.init() method. I keep getting errors stating that the directory must contain tessdata as a subfolder. I've checked that the file directory contains the folder with the trainingdata file inside, and made sure I'm pointing to the right directory. I would really like to fix this.
The directory i'm pointing to is /mnt/sdcard/Image2Text/ . I've made sure that tessdata is a subfolder with the necessary language file inside.
Here is the code:
public static final String DATA_PATH = Environment.getExternalStorageDirectory().toString() +
"/Image2Text/";
....
File dir = new File(DATA_PATH + "tessdata");
dir.mkdirs();
if (!(new File(DATA_PATH + "tessdata/" + lang + ".traineddata")).exists()) {
try {
AssetManager assetManager = getAssets();
InputStream in = assetManager.open("eng.traineddata");
OutputStream out = new FileOutputStream(DATA_PATH
+ "tessdata/eng.traineddata");
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (IOException e) {}
}
TessBaseAPI baseAPI = new TessBaseAPI();
baseAPI.init(DATA_PATH, lang);
baseAPI.setImage(new File(path));
Like you say, the DATA_PATH directory must contain tessdata as a subfolder. So, if your tessdata folder was /data/data/tessdata, DATA_PATH would be /data/data
I hope that this helps!
EDIT: ak, I think I missunderstood!

Android: How to create a directory on the SD Card and copy files from /res/raw to it?

I am trying to create a folder and several subdirectory within it on the SD Card... I then want to transfer files that I have stored in /res/raw to that folder... I addition, I want this to only happen once, the first time the program is ever run. I realize that this is ridiculously open-ended, and that I am asking a lot... but any help would be greatly appreciated.
This will copy all files in the "clipart" subfolder of the .apk assets folder to the "clipart" subfolder of your app's folder on the SD card:
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
String basepath = extStorageDirectory + "/name of your app folder on the SD card";
//...
// in onCreate
File clipartdir = new File(basepath + "/clipart/");
if (!clipartdir.exists()) {
clipartdir.mkdirs();
copyClipart();
}
private void copyClipart() {
AssetManager assetManager = getResources().getAssets();
String[] files = null;
try {
files = assetManager.list("clipart");
} catch (Exception e) {
Log.e("read clipart ERROR", e.toString());
e.printStackTrace();
}
for(int i=0; i<files.length; i++) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("clipart/" + files[i]);
out = new FileOutputStream(basepath + "/clipart/" + files[i]);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("copy clipart ERROR", e.toString());
e.printStackTrace();
}
}
}
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);
}
}
I experienced a similar problem when using mkdirs(), however because running the command:
mkdir one/two
fails on Linux, then the method http://download.oracle.com/javase/1.4.2/docs/api/java/io/File.html#mkdirs() subsequently fails too. I guess this means there is no way to use mkdirs on Android? My (probably rather hacky) work-around was to create each necessary directory separately:
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
new File(extStorageDirectory + "/one/").mkdirs();
new File(extStorageDirectory + "/one/two/).mkdirs();

Creating files in sub directories in android

Is it possible to create files in subdirectories created under "/data/data/packagename/files/" directory using openFileOutput method in android?
ie there is a sub-directory by name "text" inside the "/data/data/packagename/files/" directory.
I want to use the openFileOutput (String name, int mode) method to write a file eg:sample.txt into this directory....
Is it possible to use openFileOutput method to do it....
Can any one help me on this....
Not with openFileOutput, but you can use the regular java.io.File methods.
java.io.File.mkdir()
to create a directory, and for example for copying (can adjust for creating) a file from sdcard to some data subdir:
public static final void copyfile(String srFile, String dtFile){
Log.d(MyApp.APP,"copyfile " + srFile + " -> " + dtFile );
try{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
Log.d(MyApp.APP,"File copied to " + f2.getAbsolutePath());
} catch(FileNotFoundException ex){
Log.e(MyApp.APP,"Error.",ex);
} catch(IOException e){
Log.e(MyApp.APP,"Error.",e);
}
}

Categories

Resources