I have a FileInputStream in a class in the package com.nishu.ld28.utilities, and I want to access sound files in the folder Sounds, which is not in the com.nishu.ld28 package. I specify the path for loading like so:
"sounds/merry_xmas.wav"
And then try to load it like this:
new BufferedInputStream(new FileInputStream(path))
When I export the jar, the command line prompt that I run it through says it can't find the file. I know how to access the files when I am running the program in Eclipse, but I can't figure out how to point the FileInputStream to the Sounds folder when I export it.
Edit: As requested, here's my code:
public void loadSound(String path) {
WaveData data = null;
data = WaveData.create(GameSound.class.getClassLoader().getResourceAsStream(path));
int buffer = alGenBuffers();
alBufferData(buffer, data.format, data.data, data.samplerate);
data.dispose();
source = alGenSources();
alSourcei(source, AL_BUFFER, buffer);
}
WaveData accepts an InputStream or other types of IO.
You don't need a FileInputStream, because you aren't reading from the filesystem. Use the InputStream returned by ClassLoader.getResourceAsStream(String res) or Class.getResourceAsStream(String res). So either
in = ClassLoader.getResourceAsStream("sounds/merry_xmas.wav");
or
in = getClass().getResourceAsStream("/sounds/merry_xmas.wav");
Note the leading slash in the second example.
I would put the com.nishu.ld28.utilities in the same package of your class , let's call it MyClass.
Your package:
Your code:
package com.nishu.ld28.utilities;
import java.io.InputStream;
public class MyClass {
public static void main(String[] args) {
InputStream is = MyClass.class.getResourceAsStream("sound/merry_xmas.wav");
System.out.format("is is null ? => %s", is==null);
}
}
Output
is is null ? => false
Related
I have been happily using JUnit to run my tests and everything has been fine.
However, I now need to use Maven but for some reason it cannot find any of my resource files.
The files are in the expected place: src/main/resources
I am using the following code to try to read a file:
public Map<String, String> readCsv(String filename) {
Map<String, String> headersAsMap;
CSVDataManipulator csvDataManipulator = new CSVDataManipulator();
ClassLoader classLoader = getClass().getClassLoader();
String wrkbook = new File(classLoader.getResource(filename).getFile()).toString();
headersAsMap = csvDataManipulator.getAllRecordsAsMap(wrkbook);
return headersAsMap;
}
However, try as I might it cannot find the file.
I've tried lots of different code and tried moving the files to different locations but I cannot get Maven to find my resource files.
Any help would be greatly appreciated!
Thanks
To my understanding classLoader.getResource(..) expects the file to be in a folder structure matching the package of the class. So if the package of your class is com.matt.stuff, then you'll have to put the csv file in src/main/resources/com/matt/stuff.
Or you could just use this to grab your csv file:
private static String readFile(String fileName) throws IOException {
//filename can be src/main/resources/my-csv.csv
return new String(Files.readAllBytes(Paths.get(fileName)));
}
A File is indeed a file on the file system. For a resource which might be a file zipped in a jar, and has a path on the class path, you need something else.
Traditionally one would use a more general InputStream instead of a File.
InputStream in = getClass().getResourceAsStream("/.../x.csv"); // Path on the class path
With the new class Path, more general than File, you can deal with several (virtual) file systems:
URL url = getClass().getResource("/.../x.csv"); // Path on the class path
Path path = Paths.get(url.toURI());
Files.copy(path, Paths.get("..."));
With a bit of luck your CSVManipulator should besides being parametrized with a File, also with an InputStream or Reader (new InputStreamReader(in, "UTF-8"))
Here's my file structure of a Maven project built from the quick-start-archetype, with comons-io added as a dependency:
src
src/main
src/main/java
src/main/java/com
src/main/java/com/essexboy
src/main/java/com/essexboy/App.java
src/main/resources
src/main/resources/dir1
src/main/resources/dir1/test.txt
src/main/resources/dir2
src/main/resources/dir2/test.txt
src/main/resources/test.txt
src/test
src/test/java
src/test/java/com
src/test/java/com/essexboy
src/test/java/com/essexboy/AppTest.java
Here's my test
public class AppTest {
#Test
public void shouldAnswerWithTrue() throws Exception {
StringWriter writer = new StringWriter();
IOUtils.copy(getClass().getResourceAsStream("/test.txt"), writer, Charset.defaultCharset());
assertEquals("from root", writer.toString().trim());
writer = new StringWriter();
IOUtils.copy(getClass().getResourceAsStream("/dir1/test.txt"), writer, Charset.defaultCharset());
assertEquals("from dir1", writer.toString().trim());
writer = new StringWriter();
IOUtils.copy(getClass().getResourceAsStream("/dir2/test.txt"), writer, Charset.defaultCharset());
assertEquals("from dir2", writer.toString().trim());
}
}
I am trying to run the below sample code in java.
import java.util.Locale;
import java.util.ResourceBundle;
public class InternationalizationDemo {
public static void main(String[] args) {
ResourceBundle bundle = ResourceBundle.getBundle("MessageBundle", Locale.CANADA_FRENCH);
System.out.println("Message in "+Locale.CANADA_FRENCH +":"+bundle.getString("greeting"));
}
}
1.The above code executes properly when MessageBundle.properties is placed in the class path.
But I want to execute the above code successfully by removing the MessageBundle.properties from the classpath and placing it in some other location.
How can I do this?
Thanks in Advance.
You could use PropertyResourceBundle and get the path of your properties file from a System property for example something like that:
String configPath = System.getProperty("config.path");
ResourceBundle bundle = new PropertyResourceBundle(new FileReader(configPath));
Then in your launch command you will need to add -Dconfig.path=/path/to/my/config.properties
You can load properties file externally by this:
// Path to your file, if you have it on local, use something like C:\\MyFolder or \home\usr\etc
File file = new File("YOUR_PATH");
URL[] url = {file.toURI().toURL()};
ResourceBundle rb = ResourceBundle.getBundle("MessageBundle", Locale.CANADA_FRENCH, new URLClassLoader(url));
Example is from here: https://coderanch.com/t/432762/java/java/absolute-path-bundle-file
You are able to use remote Properties file or file which is saved on local.
I've write a Java programm and packaged it the usual way in a jar-File - unfortunately is needs to read in a txt-File. Thats way the programm failed to start on other computer machines because it could not find the txt-file.
At the same time Im using many images in my programm but here there is no such problem: I "copy" the images to the eclipse home directory, so that they are packaged in the jar-File and usable through following command:
BufferedImage buffImage=ImageIO.read(ClassName.class.getClassLoader()
.getResourceAsStream("your/class/pathName/));
There is something similar for simple textfiles which then can be use as a normal new File()?
Edit
Ive try to solve my problem with this solution:
package footballQuestioner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.security.auth.login.Configuration;
public class attempter {
public static void main(String[] args) {
example ex = new example();
}
}
class example {
public example() {
String line = null;
BufferedReader buff = new BufferedReader(new InputStreamReader(
Configuration.class
.getResourceAsStream("footballQuestioner/BackUpFile")));
do {
try {
line = buff.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} while (line != null);
}
}
But it gives always an NullPointerException...do I have forgotten something?
Here is as required my file structure of my jar-File:
You can load the file from the ClassPath by doing something like this:
ClassLoader cl = getClass().getClassLoader()
cl.getResourceAsStream("TextFile.txt");
this should also work:
getClass().getResourceAsStream(fileName);
File always points to a file in the filesystem, so I think you will have to deal with a stream.
There are no "files" in a jar but you can get your text file as a resource (URL) or as an InputStream. An InputStream can be passed into a Scanner which can help you read your file.
You state:
But it gives always an NullPointerException...do I have forgotten something?
It means that likely your resource path, "footballQuestioner/BackUpFile" is wrong. You need to start looking for the resource relative to your class files. You need to make sure to spell your file name and its extension correctly. Are you missing a .txt extension here?
Edit
What if you try simply:
BufferedReader buff = new BufferedReader(new InputStreamReader(
Configuration.class.getResourceAsStream("BackUpFile")));
In Eclipse, my directory structure is this:
-src
-com.xxx.yyy
- MyClass.java
-assets
- car.txt
MyClass.java looks like this :
public class MyClass {
private static String FILE_PATH = "../assets/car.txt";
public static void main(String[] args) {
try {
//FileNotFoundException
FileInputStream fis = new FileInputStream(new File(FILE_PATH));
}
...
}
}
I this by default, the classpath is src/, so I point to my car.txt file by ../assets/car.txt. But I get :
java.io.FileNotFoundException: ../assets/car.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
Why ?
Relative file paths a relative to the execution, assuming that the program is executed in the same location as the src and assets directory, then the path should be assets/car.txt
You can check the current execution location using System.out.println(new File(".").getCanonicalPath());
Whe you run the program it is compiled to the parent folder of the src folder as far as I know. You should better add the assets folder to your build path and access the file using getClass().getResource[AsStream]().
To add the folder do the following:
Right click on your project
Click Build Path
Choose Configure Build Path
Select Source
Click Add Folder...
Select your assets folder
Inside your code you can either call it with MyClass.class.getResource[AsStream]() or getClass().getResource[AsStream]().
getResource() returns an URL and getResourceAsStream() an InputStream. Both methods expect a path as parameter. Check the docs for more information.
Your path is incorrect
Since you are inside com.xxx.yyy, you are inside three folders. You need to get out of all of them.
So you can use, the relative path as
FILE_PATH = "../../../assets/car.txt";
As src is a source folder, all the contents come directly in the classpasth, you can also use
FILE_PATH = "assets/car.txt";
You are in second level in directory structure.
Try
FILE_PATH = "../../assets/car.txt";
Hope, this will help you...
package com.xxx.yyy;
import java.io.File;
import java.io.FileInputStream;
public class MyClass {
private static String FILE_PATH = "src/assets/car.txt";
public static void main(String[] args) {
try {
//FileNotFoundException
FileInputStream fis = new FileInputStream(new File(FILE_PATH));
}
catch (Exception e){
e.printStackTrace();
}
}
}
Ankit Lamba 's suggestion works: that's using String FILE_PATH = "assets/car.txt";
suppose I put a file a.txt in package com.xyz and the try access it like following. Will it work?
Hi All,
import com.xyz.*;
public class Hello
{
File f = new File("a.txt");
...
}
It is not working for me. Is there any workaround?
Use Class.getResource() or Class.getResourceAsStream(). see for example the Sun demo source at http://jc.unternet.net/src/java/com/sun/WatermarkDemo/WatermarkDemo.java
I will offer the same answer as jcomeau_ictx, but a lot shorter (around 30 lines in one file as opposed to >380 in 1 source file of 5), ..and with a screenshot. ;)
import javax.swing.*;
import java.net.URL;
class GetResource {
GetResource() {
Class cl = this.getClass();
final URL url = cl.getResource( cl.getName() + ".java" );
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JEditorPane ep = new JEditorPane();
try {
ep.setPage(url);
JScrollPane sp = new JScrollPane(ep);
sp.setPreferredSize(new java.awt.Dimension(400,196));
JOptionPane.showMessageDialog(null, sp);
} catch(Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(
null,
e.getMessage() + " See trace for details.");
}
}
});
}
public static void main(String[] args) {
new GetResource();
}
}
Based on your responses to the comments above. If you are looking for a work around, just specify the path to the .txt file on the file system. Putting it in a package does not help.
new File ("a.txt")
looks for a file on the the file system and not within a package.
Please also read the javadocs on File:
http://download.oracle.com/javase/6/docs/api/java/io/File.html
However I do not see the rationale in putting the file inside a package unless you would want to use it as a resource. In which case #jcomeau_ictx has the right solution
It's depend on your class path of java from where you can run this class. If both are in same place then it will work. Then no need to define path in file. But the file was not in the classpath dir then must be define path of that file otherwise file not found.