How do I address files in Asset folder? - android

I need to read "strings.json" file that lies in the "assets" folder of my Android project. But
File file = new File(filepath);
Logger.e(file.exists() ? "exists" : "doesn't exist");
says that the file doen't exist. I've tried the following variants of the filepath:
strings.json
android_asset/strings.json
/android_asset/strings.json
file:///android_asset/strings.json
What's wrong?

For read files in Assets:
InputStream is = context.getAssets().open("strings.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
fileResult = new String(buffer, "UTF-8");
In fileResult you should retrieve the content of your file.

AssetManager manager = getAssets();
try {
InputStream stream = manager.open(string+".xml");
} catch (IOException e) {
e.printStackTrace();
}

Related

Get file size from Asset

Hi I want to acces my bin file from asset folder and read file size in android.This code work for ZIP file but did not work BIN file.
try {
InputStream is = context.getAssets().open("test.bin");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
} catch (Exception e) { throw new RuntimeException(e); }
size is always 0.How can I get bin file size correctly? Thanks

Tesseract traineddata path

I am trying to use tesseract-ocr in my android app. When I am trying to init() I get IllegalArgumentException because in this folder there is no 'tessdata' dir! Here is my project structure. project structure
Here I used InputStream and cacheDir:
private String getDirPath() {
File f = new File(getCacheDir()+"/tessdata/");
if (!f.exists()) try {
InputStream is = getAssets().open("tessdata/eng.traineddata");
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("error", e.toString()); }
Log.i("wtf", f.getPath());
return getCacheDir();
}
To init the Tesseract I have to pass 2 arguments - path to dir which contains directory 'tessdata' and second one is traineddata.
Any ideas?
You can't refer to your app's raw asset files that way. Try using AssetManager instead.
The path to your assets is
Uri path = Uri.parse("file:///android_asset/")
String dataPath = path.toString();

How to load a file from assets folder of my android test project?

Is there a way to get the file object of one of the files which are inside the assets folder. I know how to load the inputstream of such a file, but i need to have a file object instead of the inputstream.
This way i load the inputstream
InputStream in2 = getInstrumentation().getContext().getResources().getAssets().open("example.stf2");
But I need the file object, this way the file will not be found
File f = new File("assets/example.stf2");
Found a soltion which works in my case, mabye someone else can use this as well.
Retrieving the file from my android test project to an inputstream
InputStream input = getInstrumentation().getContext().getResources().getAssets().open("example.stf2");
Create a file on the External-Cachedir of the android application under test
File f = new File(getInstrumentation().getTargetContext().getExternalCacheDir() +"/test.txt");
Copy the inputstream to the new file
FileUtils.copyInputStreamToFile(input, f);
Now I can use this file for my further tests
try below code:-
AssetManager am = getAssets();
InputStream inputStream = am.open(file:///android_asset/myfoldername/myfilename);
File file = createFileFromInputStream(inputStream);
private File createFileFromInputStream(InputStream inputStream) {
try{
File f = new File(my_file_name);
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
return f;
}catch (IOException e) {
//Logging exception
}
return null;
}
for more info see below link :-
How to pass a file path which is in assets folder to File(String path)?

Android get data from json file (.txt)

I have Json file (test.txt) and I wanna get data from that file to Android App. My code is:
private static String url = "file:///AndroidJSONParsingActivity/res/raw/test.txt";
But it is not working. Error I get is:
error opening trace file: No such file or directory (2)
Somebody help me? Thanks!
Put the test.txt file into assets folder
public class Utility {
public static String readXMLinString(String fileName, Context c) {
try {
InputStream is = c.getAssets().open(fileName);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String text = new String(buffer);
return text;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Then you can get test.txt using the following code
JSONObject json = new JSONObject(Utility.readXMLinString("test.txt",getApplicationContext()));
You have an answere Using JSON File in Android App Resources
You need to put the file intro raw folder and you can acces with this:
getResources().openRawResource(resourceName)
use getResources().openRawResource(RawResource_id) for reading an text file from res/raw folder as:
InputStream inputStream = Current_Activity.this.
getResources().openRawResource(R.raw.test);
//put your code for reading json from text file(inputStream) here
use following code to open input stream for the file stored in the raw folder:
getResources().openRawResource(R.raw.text_file)
Please see below code for that, it will solve your problem.
public void mReadJsonData() {
try {
InputStream is = getResources().openRawResource(R.raw.textfilename)
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String mResponse = new String(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

how to read .pdf file in assets folder

File file = new File("android.resource://com.baltech.PdfReader/assets/raw/"+filename);
if (file.exists()) {
Uri targetUri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(targetUri, "application/pdf");
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText(PdfReaderActivity.this, "No Application Available to View PDF", Toast.LENGTH_SHORT).show();
}
i want to read .pdf file which is in assets folder. what path i hav to give in filename. plz help. Thanks
I'm not sure if you got an answer to this already, seems pretty old, but this worked for me.
//you need to copy the input stream to a new file, so store it elsewhere
//this stores it to the sdcard in a new folder "MyApp"
String filename = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyApp/solicitation_form.pdf";
AssetManager assetManager = getAssets();
try {
InputStream pdfFileStream = assetManager.open("solicitation_form.pdf");
CreateFileFromInputStream(pdfFileStream, filename);
} catch (IOException e1) {
e1.printStackTrace();
}
File pdfFile = new File(filename);
The CreateFileFromInputStream function is as follows
public void CreateFileFromInputStream(InputStream inStream, String path) throws IOException {
// write the inputStream to a FileOutputStream
OutputStream out = new FileOutputStream(new File(path));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
inStream.close();
out.flush();
out.close();
}
Really hope this helps anyone else who reads this.
File file = new File("file:///android_asset/raw/"+filename);
replace the above line with below and try..
File file = new File("android.resource://com.com.com/raw/"+filename);
and place your PDF file raw folder instead of asset. Also change com.com.com with your package name.
Since assets files are stored inside apk file, there is no absolute path of the assets folder.
You might use a workaround creating a new file used as a buffer.
You should use AssetManager:
AssetManager mngr = getAssets();
InputStream ip = mngr.open(<filename in the assets folder>);
File assetFile = createFileFromInputStream(ip);
private File createFileFromInputStream(InputStream ip);
try{
File f=new File(<filename>);
OutputStream out=new FileOutputStream(f);
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0)
out.write(buf,0,len);
out.close();
inputStream.close();
}catch (IOException e){}
}
}

Categories

Resources