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();
}
Related
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"
I have created own jar with native library wrapper. The structure of resulting jar is:
library.jar
|- com (there are my .java classes)
|- libs (there is the native - libmylib.so)
|- META-INF
I load native lib as follows:
MyLibClass instance = (MyLibClass) Native.loadLibrary("mylib", MyLibClass.class);
Now I want to add this library in other project and use it. But when I create an instance of MyLibClass I receive an error:
Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load library 'mylib':
libmylib.so: cannot open shared object file: No such file or directory
How should i fix this problem?
As noted on the JNA Getting Started page,
Make your target library available to your Java program. There are several ways to do this:
The preferred method is to set the jna.library.path system property to the path to your target library. This property is similar to java.library.path, but only applies to libraries loaded by JNA.
Change the appropriate library access environment variable before launching the VM. This is PATH on Windows, LD_LIBRARY_PATH on Linux, and DYLD_LIBRARY_PATH on OSX.
Make your native library available on your classpath, under the path {OS}-{ARCH}/{LIBRARY}, where {OS}-{ARCH} is JNA's canonical prefix for native libraries (e.g. win32-x86, linux-amd64, or darwin). If the resource is within a jar file it will be automatically extracted when loaded.
I've done that using static Loader class as follows:
static class Loader {
private Loader() {
}
static String getNative() {
InputStream in = null;
FileOutputStream fos = null;
File fileOut = null;
System.setProperty("jna.library.path",
System.getProperty("java.io.tmpdir"));
in = Loader.class.getResourceAsStream(
"/libs/libmylib.so");
if (in != null) {
try {
fileOut = File.createTempFile("mylib", ".so");
fileOut.deleteOnExit();
fos = new FileOutputStream(fileOut);
int count;
byte[] buf = new byte[1024];
while ((count = in.read(buf, 0, buf.length)) > 0) {
fos.write(buf, 0, count);
}
} catch (IOException ex) {
throw new Error("Failed to create temporary file: " + ex);
} finally {
try {
in.close();
} catch (IOException ex) {
}
if (fos != null) {
try {
fos.close();
} catch (IOException ex) {
}
}
return fileOut.getAbsolutePath();
}
} else {
throw new Error("Couldn't open native library file");
}
}
}
There I load library file from resources and copy its contents to the temporary dir. As you can see before doing that I set jna.library.path to temp folder, so JNA will search libraries there.
Futher I'm loading library as this:
MyLibClass instance = (MyLibClass) Native.loadLibrary(Loader.getNative(), MyLibClass.class);
How come my file isn't being read correctly? I checked, and the res folder is a resource in this project.
public class Testing {
private File file;
private Clip clip;
private AudioInputStream audioIn;
public Testing() {
String path = "/res/shot.mp3";
file = new File(path);
System.out.println(file.toString());
try {
audioIn = AudioSystem.getAudioInputStream(file);
clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();
} catch(Exception e) {
e.printStackTrace();
}
// java.io.FileNotFoundException: \res\shot.mp3
// (The system cannot find the path specified)
}
public static void main(String[] args) {
new Testing();
}
}
My Package Explorer.
I tried changing the path to /SoundTest/res/shot.mp3, still no luck. Any ideas?
/res/shot.mp3 is an absolute path. This will only work if res is in the root directory of your file system. You say "The resource folder is a folder in this project". From your screenshot, the directory structure is something like
/home/your_user_dir/your_project_dir
/src ...
/bin
/res
So you need to change the creation of your File object such that either it has the correct relative path, or uses an absolute path.
You can use
InputStream is = this.getClass().getClassLoader().getResourceAsStream("/res/shot.mp3");
and then create your AudioInputStream with AudioSystem.getAudioInputStream(InputStream) -- documentation
So change your code to
String path = "/res/shot.mp3";
InputStream is = this.getClass().getClassLoader().getResourceAsStream(path);
try {
audioIn = AudioSystem.getAudioInputStream(is);
clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();
} catch(Exception e) {
e.printStackTrace();
}
Regardless of the file beeing present, are you sure you want to use a .mp3-file? AudioSystem.getAudioFileTypes() returns WAVE, AU and AIFF as supported types on my machine.
Furthermore is the exception you are presenting in your question matching the source code you shared? In your code its shot.mp3, but the exception refers to a .wav file.
No you cannot use
file = new File(path);
audioIn = AudioSystem.getAudioInputStream(file);
If you want to get the file in the resources folder you have to get using the Method getResource()
Change this in your code :
URL url = Testing.class.getResource("/res/shot.mp3");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
Clip clip = AudioSystem.getClip();
clip.open(audioIn);//surround with try catch block i didn't use here
hope this may helpful
If I have the following directory structure,
+src
++com.foo.util
+++FooProperties.java
+foo.properties
How do I reference foo.properties as a resource stream in FooProperties? I've tried adding it to the classpath and referencing it as such,
FooProperties.class.getResourceAsStream("/foo.properties")
but I get a NullPointerException. What am I doing wrong?
If you want to keep the properties file outside the src(same level as src), then you can fetch your properties file this way:-
try {
InputStream fileStream = new FileInputStream(new File(
"test.properties"));
Properties props = new Properties();
props.load(fileStream);
String myPropValue = (String) props.get("test.prop");
System.out.println(myPropValue);
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
Hope it helps. You can even edit the properties file using the above method(no absolute path required).
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