Reading files inside a APK - java

I am having an android application that is using an external jar that
has in addition to regular classes an html file.
Meaning my final apk root directory looks something like this
assests
res
AndroidManifest.xml
classes.dex
resources.arsc
helloworld.html
How can I access from my application to the last file
"helloworld.html"?

Android package hierarchy is not a like java application package.
So you can't access files like this.
I think you have to use this helloworld.html file in your application.
So put this file in /asset directory and in your activity code just get file using
getAssets().
also access file like: file:///android_asset/helloworld.html

Why not making a library project instead of a jar?

You have to replace the string "assets/SecureManifest.xml" with your file "helloworld.html"
public static InputStream getInputStreamFromApkResource(String apkFilePath, String apkResPath) throws IOException {
JarFile jarFile = new JarFile(apkFilePath);
JarEntry jarEntry = jarFile.getJarEntry(apkResPath);
return jarFile.getInputStream(jarEntry);
}
// Example usage reading the file "SecureManifest.xml" under "assets" folder:
File sdcard = Environment.getExternalStorageDirectory();
File apkFile = new File(sdcard, "file.apk");
if (apkFile.exists()) {
try {
InputStream is =getInputStreamFromApkResource(apkFile.toString(), "assets/SecureManifest.xml");
BufferedReader br = new BufferedReader( new InputStreamReader(is));
String str;
while ((str = br.readLine()) != null) {
Log.d("***", str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
The github gist can be found here

Related

java.nio.file.AccessDeniedException error?

Im trying to zip my created folder. Right now im testing localy and it create folder but after that i want to zip it.
This is my code for zip:
public static void pack(final String sourceDirPath, final String zipFilePath) throws IOException {
Path p = Files.createFile(Paths.get(zipFilePath));
try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(p))) {
Path pp = Paths.get(sourceDirPath);
Files.walk(pp).filter(path -> !Files.isDirectory(path)).forEach(path -> {
ZipEntry zipEntry = new ZipEntry(pp.relativize(path).toString());
try {
zs.putNextEntry(zipEntry);
Files.copy(path, zs);
zs.closeEntry();
} catch (IOException e) {
System.err.println(e);
}
});
} }
But im getting an error AccessDeniedException. Is there any option to zip created folder, i dont want to zip file because in that folder i will have subfolders, so i want to zip main folder. Any suggestion how can i achive that?
According to:
Getting "java.nio.file.AccessDeniedException" when trying to write to a folder
I think you should add the filename and the extension to your 'zipFilePath', for example: "C:\Users\XXXXX\Desktop\zippedFile.zip"

Can not read file when run within jar file

I have an akka http service. I simply return the api documentation for a get request. The documentation is in html file.
It all works fine when run within the IDE. When I package it as a jar I get error 'resource not found'. I am not sure why it can not read the html file when hosted in a jar and works fine when in IDE.
Here is the code for the route.
private Route topLevelRoute() {
return pathEndOrSingleSlash(() -> getFromResource("asciidoc/html/api.html"));
}
The files are located in resource path.
I have got this working now.
I am doing this.
private Route topLevelRoute() {
try {
InputStreamReader inputStreamReader = new InputStreamReader(getClass().getResourceAsStream("/asciidoc/html/api.html"));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//Get the stream input into string builder
reader.lines().forEach(s -> strBuild.append(s));
inputStreamReader.close();
bufferedReader.close();
//pass the string builder as string with contenttype set to html
complete(HttpEntities.create(ContentTypes.TEXT_HTML_UTF8, strBuild.toString()))
} catch (Exception ex) {
//Catch any exception here
}
}

Using static resources inside a jar library (to be used in Android)

I am developing a plain java library (jar), which contains some static files, which I put to src/main/resources. These static files are used to execute an algorithm and return processed data to the user.
public String getStringFromFile(String fileName) {
String text = "";
try {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
Scanner scanner = new Scanner(file);
text = scanner.useDelimiter("\\A").next();
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return text;
}
So far so good. However, when I try to use this library/method in an Android project I get:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.net.URL.getFile()' on a null object reference
I want my static resource files to be published with the library. Am I doing something wrong? Any thoughts?
Ok. I think I have solved this. Following this article I created a res directory in the root of my jar module (on the same level as the src directory) and put my files there (helloworld.json). Then added this to build.gradle:
jar {
into('resourcez') {
from 'res'
}
}
Using this helper function (inside the jar lib) and getResourceAsStream() I get the contents of my resource files:
public String getModelFromStream(String fileName) {
final String classpath = "resourcez/";
ClassLoader classLoader = DexiModelLoader.class.getClassLoader();
InputStream resourceAsStream = classLoader.getResourceAsStream(fileName);
if (resourceAsStream == null)
resourceAsStream = classLoader.getResourceAsStream(classpath + fileName);
if (resourceAsStream == null)
return "error";
Scanner s = new Scanner(resourceAsStream).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
After this I simply call getStringFromStream("helloworld.json") or getStringFromStream("resourcez/helloworld.json") in my android app and voilĂ !

Read from file but I didn't see in android?

I want to read from txt file and send to TextView. My method works on Java Project I read and I see System.out.print but the same method doesnt work in MainActivity. How can I fixed.Thanks
MainActivity
public class MainActivity extends Activity {
TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt=(TextView)findViewById(R.id.textView1);
Parsing p =new Parsing();
try {
String gelen=p.readTxt();
txt.setText(gelen);
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Parsing:
public class Parsing {
public String readTxt() throws FileNotFoundException
{
File file = new File("C:\\Users\\John\\Desktop\\try.txt");
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner = new Scanner(file);
String lineSeparator = System.getProperty("line.separator");
try {
while(scanner.hasNextLine()) {
fileContents.append(scanner.nextLine() + lineSeparator);
}
return fileContents.toString();
} finally {
scanner.close();
}
}
}
I'm working it but I see just TextView.
you cannot specify the computer directory files to the android file path location to read lines in it.
just put the file into your android project folder like assests and change the
path and then try.
How can I read a text file in Android?
I don't mean to be rude but try to search first. This question with similar problem was already asked.
I hope this link will help you.
Cheers
For file on sdcard ("sdcard\myfolder\1.txt") please use:
File file = new File(Environment.getExternalStorageDirectory(), "myfolder\1.txt");
Also dont forget:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
You must put the file in the asset folder of your project.
Then to access it you can do something like
BufferedReader reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt")));
for more details read my answer here :
read file from assets
First of all Android Application Project is different from Java Project.
You can not use File file = new File("C:\\Users\\John\\Desktop\\try.txt"); in android.
Place your text file in the /assets directory under the Android project. Use AssetManager class to access it.
AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");
If you are going to access file from memory card, Then use inputsteram is in your program. Also you need the following permission to read the text file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Android resource files

I have a cheerapp.mp3 in my /res/raw folder
so my code is
String filepath="/res/raw/cheerapp"; //or cheerapp.mp3
file = new File(filePath);
FileInputStream in = null;
try {
in = new FileInputStream( file );
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The error I got file not found. why?
Use assets folder and ...
InputStream sound = getAssets().open("filename.mp3");
... or raw folder and ...
InputStream sound = getResources().openRawResource(R.raw.filename);
if it doesn't help you, then check this
Never can you access resource files by path!
Because they are compiled in APK file installed in Android. You can only access resource within application by access its generated resource id, from any activity (context):
InputStream cheerSound = this.getResources().openRawResource(R.raw.cheerapp);
or from view:
InputStream cheerSound = this.getContext().getResources().openRawResource(R.raw.cheerapp);
In your case, you should store sound files in external sd-card, then can access them by path. For e.g, you store your file in sounds folder on your sd-card:
FileInputStream inFile = new FileInputStream("/mnt/sdcard/sounds/cheerapp.mp3");
NOTE: path starts with '/' is absolute path, because '/' represents root in Unix-like OS (Unix, Linux, Android, ...)
Maybe you could use the AssetManager to manage your resources. For example:
AssetManager manager = this.getContext().getAssets();
InputStream open;
try {
open = manager.open(fileName);
BitmapFactory.Options options = new BitmapFactory.Options();
...
} catch (IOException e) {
e.printStackTrace();
}

Categories

Resources