Creating files in sub directories in android - 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);
}
}

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());
}
}
}

Files.list returns null for android data/data device is rooted

I'm trying to generate a list of all the files in a particular directory in /data/data/ e.g. /data/data/com.package.ect so that I can zip them. My device is rooted and I've granted Super User to my app. When pass the path to the directory it gets past the if statement, so it recognises that what I'm trying to access is a directory, yet File.list() returns null. I'm assuming I'm still lacking some sort of permission.
/**
* Traverse a directory and get all files,
* and add the file into fileList
* #param node file or directory
*/
public void generateFileList(File node) {
//add file only
if (node.isFile()) {
fileList.add(generateZipEntry(node.getAbsoluteFile().toString()));
}
if (node.isDirectory()) {
String[] subNote = node.list();
for (String filename : subNote) {
generateFileList(new File(node, filename));
}
}
}
*EDIT: As requested where generateFileList is called
public void zipDirectory(String outputPath){
byte[] buffer = new byte[1024];
try{
checkStorageDirExists(SDCARD, STORAGE_LOCATION);
generateFileList(new File(path));
FileOutputStream fos = new FileOutputStream(SDCARD + STORAGE_LOCATION + outputPath);
ZipOutputStream zos = new ZipOutputStream(fos);
setZipFileName(path);
Log.i(TAG, "Output to Zip : " + outputPath);
for(String file : this.fileList){
System.out.println("File Added : " + file);
ZipEntry ze= new ZipEntry(file);
zos.putNextEntry(ze);
FileInputStream in =
new FileInputStream(path + "/" + file);
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in.close();
}
zos.closeEntry();
zos.close();
Log.i(TAG, "Zip of " + getZipFileName() +" Completed");
}catch(IOException ex){
ex.printStackTrace();
}

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();

what is the folder of sdcard and how can i create files and read and write them in it

please somebody tell me what is the folder of sdcard and how can i create files in it.because i am new to android and i have googled so much but could not find any comprehensive stuff.i want to create file in sdcard manually. please help.
here is my code i have written but now it says fileNotFoundException. hence i have created a file in sdcard but still it is not recognisizing the file.any suggestions please.
try
{
String root = android.os.Environment.getExternalStorageDirectory().getPath();
File gpxfile = new File(root, "sijjeel.txt");
//FileWriter writer = new FileWriter(gpxfile);
FileOutputStream writer = new FileOutputStream(gpxfile);
writer.write(bArray, 0, bArray.length);
writer.flush();
writer.close();
}
thanks alot
Path to sdcard is:
android.os.Environment.getExternalStorageDirectory().getPath()
To write a file, you can use the regular java.io.File methods for that.
For example, for creating a text files I use a helper method like this:
/**
* Stores text content into a file
* #param filename Path to the output file
* #param content Content to be stored in file
* #throws IOException
*/
public void storeFile(final String filename, final String content, String charSet)
throws IOException {
if (charSet==null) charSet = "utf-8";
Writer w = new OutputStreamWriter( new FileOutputStream(filename), charSet );
w.write(content);
w.flush();
w.close();
}
public void storeFile(final String filename, final String content)
throws IOException {
storeFile(filename, content, null);
}
or copying a file to sdcard:
public static final void copyfile(String srFile, String 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();
System.out.println("File copied to " + f2.getAbsolutePath());
} catch(FileNotFoundException ex){
System.out.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
} catch(IOException e){
System.out.println(e.getMessage());
}
}
It's /sdcard (if you actually have a card in it)
The code you provided will create the file if it is not already there. Make sure you run your program on the emulator that has an SD card mounted. If it doesn't you can see an icon in the notification area saying so.

Categories

Resources