Get path of data directory(android) - android

I am using tesseract ocr in my app. In order to use tesseract i need to use several language files that are located at a directory called - 'tessdata'.
This is my method code:
public String detectText(Bitmap bitmap) {
TessBaseAPI tessBaseAPI = new TessBaseAPI();
String DATA_PATH = Environment.getRootDirectory().getPath() + "/tessdata/";
tessBaseAPI.setDebug(true);
tessBaseAPI.init(DATA_PATH, "eng"); //Init the Tess with the trained data file, with english language
tessBaseAPI.setImage(bitmap);
String text = tessBaseAPI.getUTF8Text();
tessBaseAPI.end();
return text;
}
I've used many variations of:
String DATA_PATH = Environment.getRootDirectory().getPath() + "/tessdata/";
and every time the app fails with "path not found" exception.
I need a good way to put this directory in the android phone and get the path of it regardless of which phone it is. Right now the 'tessdata' directory can be found at the app root directory.
How can i do that?

Don't include "/tessdata/" in your DATA_PATH variable--just leave that part off, but be sure that subfolder exists within the directory specified by DATA_PATH.

From sourcecode TessBaseAPI#init
public boolean init(String datapath, String language) {
...
if (!datapath.endsWith(File.separator))
datapath += File.separator;
File tessdata = new File(datapath + "tessdata");
if (!tessdata.exists() || !tessdata.isDirectory())
throw new IllegalArgumentException("Data path must contain subfolder tessdata!");
That means
the tessdata-subdirectory must exist.
init gets the parent-folder of "tessdata"
You can create it like this:
File dataPath = Environment.getDataDirectory();
// or any other dir where you app has file write permissions
File tessSubDir = new File(dataPath,"tessdata");
tessSubDir.mkdirs(); // create if it does not exist
tessBaseAPI.init(dataPath.getAbsolutePath(), "eng");

Related

Where to store files for user in Android?

I have to export files from my application and looking for a solution, where I can save files, to give the user the possibility to open them.
I tried already getFilesDir().getPath() which worked well, until I realized that the folder can't open from a real device (/data/user/0/com.myapplication.example/files) since the /data path is just a storage area for the application.
What are the alternatives?
You should have a look here https://developer.android.com/training/data-storage
I'm not sure what file type you are trying to store however what you have tried stores the file withing the applications directory and not the devices. To combat this I would look under either Media or Documents and other files again in the above link. I would be able to be of further assistance if I knew what file type you are trying to store. Hope this helps you in some way.
This is a function to store a float array to the phone external storage. Pass the file name.extension in the String name. You could modify it to export your file.
public static void save(float[] input_array, String name)
{
final String TAG2 = "->save()";
String string_array = Arrays.toString(input_array);
String fullName = Environment.getExternalStorageDirectory().getPath() + "/SercanFolder/" + name;
String path = Environment.getExternalStorageDirectory().getPath() + "/SercanFolder";
File folder = new File(path);
if(!folder.exists())
{
folder.mkdirs();
}
BufferedWriter buf;
try
{
buf = new BufferedWriter(new FileWriter(fullName));
buf.write(string_array,0,string_array.length());
buf.close();
Log.d(TAG+TAG2, "array saved as document. ");
}
catch (IOException e)
{
Log.e(TAG+TAG2, "problems while saving the file. ");
}
}
The suggestion with getExternalStorage().getPath() (Thanks to blackapps) helped me to save the pdf in a folder, which can be opened in the file manager.

remove unused files from storage

I saved some images in my storage's specific folder.I have fro example 1.png,2.png and etc. I know how i can get all files's name.This is source
private void getAllElemetsFromStorage() {
String root_sd = Environment.getExternalStorageDirectory().toString();
File file = new File(root_sd + "/myfolder");
for (File f : file.listFiles()) {
if (f.isFile()) {
String name = f.getName();
Log.e("file names", name + "");
}}
}
This code working correct but i have one problem.I have some json and in my json i have file's name.How i can get all files name witch is not in my json and is my directory and how i can delete all this files? My goal is to save only files,witch are in my jsons and i want to delete all unused files from my directory
How i can solve my problem?
thanks
Inside your if statement, after you get the file name, loop through the json and check whether its in there or not. If not, delete it.
Your for loop that exists already will do this for every file in the directory, removing it if the name doesnt exist in the json.
Below is an example. Depending on your Json, you need to build a list or loop through another way.
private void getAllElemetsFromStorage() {
String root_sd = Environment.getExternalStorageDirectory().toString();
File file = new File(root_sd + "/myfolder");
ArrayList<String> jsonFileNames = // Get list of file names from json
for (File f : file.listFiles()) {
if (f.isFile()) {
String name = f.getName();
// If not found in json. Delete file
if(!jsonFileNames.contains(name))
f.delete();
}
}
}
Note: this code is untested so may be typos. But it should give you the idea.

Unity 3D Android and File

I have a problem with Android and Unity 3D. I have a file read code. When I put my code on the computer, it works. However, my code does not work on Android (Mobile). How can I solve this problem? Thank you.
FileInfo theSourceFile = new FileInfo(filename);
if (System.IO.File.Exists(fname))
{
StreamReader reader = theSourceFile.OpenText();
string text = reader.ReadLine();
print(string);
}
EDIT updated code
string filename = "file.txt";
FileInfo theSourceFile = new FileInfo(filename);
filename = Application.persistentDataPath + "/"+filename;
System.IO.File.WriteAllText(filename,"Test");
if (System.IO.File.Exists(filename))
{
StreamReader reader = theSourceFile.OpenText();
string text = reader.ReadLine();
print(string);
}
You need to change your build settings for android Device.
Change Configuration >> write access to external (sd card).
if not, your app is pointing to internal path and you need root permission in your android device.
You must use Application.persistentDataPath on Android to be able to read anything.
Change that to string filename = Application.persistentDataPath + "/file.txt"; and your code should work fine.
Bear in mind that before the read function can work, you must write to the directory first. So file.txt must exist in Application.persistentDataPath first.
For example
string filename = Application.persistentDataPath + "/file.txt";
System.IO.File.WriteAllText(filename,"Test");
EDIT:
You new code is still not working because you had FileInfo theSourceFile = new FileInfo(filename); before filename = Application.persistentDataPath + "/"+filename;. This means that the file name is still not valid. Pay attention the order your script execute. After switching it, it worked on my Android. Below is the whole code.
string filename = "file.txt";
filename = Application.persistentDataPath + "/" + filename;
System.IO.FileInfo theSourceFile = new System.IO.FileInfo(filename);
System.IO.File.WriteAllText(filename, "Test");
if (System.IO.File.Exists(filename))
{
System.IO.StreamReader reader = theSourceFile.OpenText();
string text = reader.ReadLine();
print(text);
}

Saving file in sd card without extension and access that with extension

I am downloading a pdf file from server and saving it on sd card without extension (for security purpose so that normal user can't open that file from file manager).For e.g.- I am downloading abc.pdf and saving it on sd card with abc on below path
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "files");
And later I want to view that file by adding extension.
So when I am accessing that file from code by using below code then its gives error file does't exist..
String s=Environment.getExternalStorageDirectory() + "/files/" + "abc";
File pdfFile = new File(s+".pdf");
So how can I save file in sd card without extension and later open that file with extension.
Workaround for your problem is to rename your saved pdf file without extension to filename with .pdf extension & after completing/accessing view or read operation on your new pdf extension file again you can rename it to file without extension
Example Usage:
String currentFileName = Environment.getExternalStorageDirectory() + File.separator
+ "files" + File.separator + "abc";
String renamedFilename = currentFileName + ".pdf";
boolean isRenamed = renameFile(currentFileName, renamedFilename);
Log.d("isRenamed: ", "" + isRenamed);
if(isRenamed {
//perform your operation
}
Again rename the file if not in use (here exchange renameFile() parameters):
boolean renameAfterOperation = renameFile(renamedFilename, currentFileName);
Log.d("renameAfterOperation : ", "" + renameAfterOperation );
And here is renameFile(currentFilePath, renamedFilePath):
public boolean renameFile(String currentFilePath, String renamedFilePath){
File currentFile = new File(currentFilePath);
File newFile = new File(renamedFilePath);
boolean isrenamed = currentFile.renameTo(newFile);
return isrenamed;
}
In this way whenever you want to perform operation on saved file first rename it to .pdf & whenever it's not in use, again rename it without extension. Let me know if this works for you..

creating a file and all parent directories

is there a method that allows in Android 2.1 to create a new file and, if relative directories do not exist, to create them too?
make me know, 'cause this snippet does not work:
static String separator = File.separator;
public static final String DIRECTORYBIGLIETTI = "C:" + separator + "Users" + separator + "7-Spode" + separator + "Documents" + separator + "Android" + separator + "HUVWSZE"; ///sdcard/.SpodeApps/HUVWSZE/
public static final String FILEBIGLIETTI = DIRECTORYBIGLIETTI.concat(separator + "lista.txt");
File cartellainputoutput = new File(DIRECTORYBIGLIETTI);
if(!cartellainputoutput.exists())
{
cartellainputoutput.mkdirs();
}
File fileinputoutput = new File(FILEBIGLIETTI);
if(!fileinputoutput.exists())
try {
fileinputoutput.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
may i ask to the admin for upgrading this web site's graphics? ;)
You need to use mkdirs() to create the directories, and then create the file.
Just to make this clear, you cannot use Windows-like file paths (such as C:\Users\7-Spode\Documents\Android\HUVWSZE) in Android, you have to use Linux-like file paths (like /data/my.android.application/data_directory/file or /sdcard/directory/file.
Also, you should use methods such as getFilesDir() (for internal storage) and getExternalStorageDirectory() (for external storage, e.g. SD cards) to get those directories, and from there you can just create a regular File object and handle it from there.
Example (with internal storage):
File dir = getFilesDir(); // Returns a directory exclusively for this app.
File file = new File(dir, "directory/file");
file.mkdirs();
file.createNewFile();
Also note that when working with external storage, you should always check if external storage is unavailable (for instance if SD card has been removed, or the device is connected
to a computer), using getExternalStorageState().
For more information about how to use internal and external storage in Android, read this nifty article.

Categories

Resources