getClass().getResource() in static context - java

I'm trying to get a resource (image.png, in the same package as this code) from a static method using this code:
import java.net.*;
public class StaticResource {
public static void main(String[] args) {
URL u = StaticResource.class.getClass().getResource("image.png");
System.out.println(u);
}
}
The output is just 'null'
I've also tried StaticResource.class.getClass().getClassLoader().getResource("image.png");
, it throws a NullPointerException
I've seen other solutions where this works, what am I doing wrong?

Remove the ".getClass()" part.
Just use
URL u = StaticResource.class.getResource("image.png");

Always try to place the resources outside the JAVA code to make it more manageable and reusable by other package's class.
You can try any one
// Read from same package
URL url = StaticResource.class.getResource("c.png");
// Read from same package
InputStream in = StaticResource.class.getResourceAsStream("c.png");
// Read from absolute path
File file = new File("E:/SOFTWARE/TrainPIS/res/drawable/c.png");
// Read from images folder parallel to src in your project
File file = new File("images/c.jpg");
// Read from src/images folder
URL url = StaticResource.class.getResource("/images/c.png")
// Read from src/images folder
InputStream in = StaticResource.class.getResourceAsStream("/images/c.png")

Related

Get file from class path so tests can run on all machines

I am using Vertx and trying to test some parameters that i am getting data from jsonfile, currently it works but i want get this file just through class path so it can be tested from a different computer.
private ConfigRetriever getConfigRetriever() {
ConfigStoreOptions fileStore = new ConfigStoreOptions().setType("file").setOptional(true)
.setConfig(new JsonObject()
.put("path", "/home/user/MyProjects/MicroserviceBoilerPlate/src/test/resources/local_file.json"));
ConfigStoreOptions sysPropsStore = new ConfigStoreOptions().setType("sys");
ConfigRetrieverOptions options = new ConfigRetrieverOptions().addStore(fileStore).addStore(sysPropsStore);
return ConfigRetriever.create(Vertx.vertx(), options);
}
My path as written above starts from /home / dir which makes it impossible to be tested on another machine. My test below uses this config
#Test
public void tourTypes() {
ConfigRetriever retriever = getConfigRetriever();
retriever.getConfig(ar -> {
if (ar.failed()) {
// Failed to retrieve the configuration
} else {
JsonObject config = ar.result();
List<String> extractedIds = YubiParserServiceCustomImplTest.getQueryParameters(config, "tourTypes");
assertEquals(asList("1", "2", "3", "6"), extractedIds);
}
});
}
I want to make the path a class path so i can test it on all environment.
I tried to access class path like this but not sure how it should be
private void fileFinder() {
Path p1 = Paths.get("/test/resources/local_file.json");
Path fileName = p1.getFileName();
}
If you have stored the file inside "src/test/resources" then you can use
InputStream confFile = getClass().getResourceAsStream("/local_file.json");
or
URL url = getClass().getResource("/local_file.json");
inside your test class (example)
IMPORTANT!
In both cases the file names can start with a / or not. If it does, it starts at the root of the classpath. If not, it starts at the package of the class on which the method is called.
Put .json file to /resources folder of your project (here an example).
Then access it via ClassLoader.getResourceAsStream:
InputStream configFile = ClassLoader.getResourceAsStream("path/to/file.json");
JsonObject config = new JsonParser().parse(configFile);
// Then provide this config to Vertx
As I understand, considering the location of your json file, you simply need to do this:
.setConfig(new JsonObject().put("path", "local_file.json"));
See this for reference.

Load a file from a specific directory

I have a specified URL that i cant change i.e.
/opt/local/java/config/npvr.properties
where should i place my file so that the following code can work:
String PROPERTIESFILEPATH1 = "/opt/local/java/config/npvr.properties";
File tmPropertiesFile = new File(PROPERTIESFILEPATH);
Properties properties = new Properties();
if (tmPropertiesFile.exists()) {
.....
}
i have tried placing my file in directory shown below but it didn't work:
My problem is that I can change only the location of property-file without changing the code to solve this problem. Please Help.
The file needs to go in /opt/local/java/config, not [projectdir]/opt/local/java/config. You are putting it in the wrong place
If you are using linux then add this file /opt/local/java/config/ directory location outside of your project.
"OR"
in windows C:\opt\local\java\config\ here.
use getClass().getResourceAsStream to load property file from relative of class
public class Main {
public static void main(String args[]) throws Exception{
String PROPERTIESFILEPATH = "/opt/local/java/config/npvr.properties";
//File tmPropertiesFile = new File(PROPERTIESFILEPATH);
Properties properties = new Properties();
InputStream ins=null;
//ins=new FileInputStream(PROPERTIESFILEPATH);
ins=new Main().getClass().getResourceAsStream(PROPERTIESFILEPATH);
properties.load(ins);
System.out.println(properties.get("Hello"));
}
}

How to use relative paths in the given below code?

Consider the code sample below. Migrator class takes two input files, processes it and writes the output to final.tbl.
I want final.tbl to be created on the same path where the folder of input files is present.
Also the execute method should take relative path of this generated final.tbl file.
public class Migrator{
public void Migrate(String path1,String path2){
PrintStream out = new PrintStream("final.tbl");//I need relative path as that of input folder path i.e path1,path2
//.....
//.....Processing
}
}
class MainProcess{
public execute(String path){
//here the execute method should the the relative path of above final.tbl file
}
public static void main(String args[]){
}
}
Path path = Paths.get(path1);
PrintStream out = new PrintStream(path.getParent().toString() + "\\final.tbl");
I think you can use getAbsolutePath to get path to your input files:
public class Migrator{
public void Migrate(String path1,String path2){
File f = new File(path1);
String absolutePath = f.getAbsolutePath(); // use absolutePath for your PrintStream
PrintStream out = new PrintStream(absolutePath);//I need relative path as that of input folder path i.e path1,path2
//.....
//.....Processing
}
}
Hope it helped
Use the getParentFile()
File target = new File(new File(path1).getParentFile(), "final.tbl");
PrintStream out = new PrintStream(target);

java.net.URL refer to a file in a parent directoty

I have a very basic question. I need a URL object but the file is in the previous directory relative to the project.
For instance, if I do
File testFile = new File("../../data/myData.xml");
works perfectly fine, it finds the file
However,
URL testURL = new URL("file:///../../data/myData.xml")
gives an
Exception in thread "main" java.io.FileNotFoundException: /../../data/myData.xml
Any idea, how to solve, work around this? without changing the position of the data?
Thanks a lot in advance
Altober
you can use this
URL testURL = new File("../../data/myData.xml").toURI().toURL();
/**
* #param args
*/
public static void main(String[] args) {
try {
URL testUrl = new URL("file://C:/Users/myName/Desktop/abc.txt");
System.out.println(testUrl.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
The above code is working file, just tested it, so you need to use file:// and if possible try full path
Exception in thread "main" java.io.FileNotFoundException: /../../data/myData.xml
Note that it is looking for parent directory of root directory, not of current directory.
I dont know if File URLs can refer to relative paths, try
‘new URL("file://../../data/myData.xml")'‘

Java: opening a resource (txt file) which is in a jar with OS standard application

i get the error "AWT-EventQueue-0 java.lang.IllegalArgumentException: URI is not hierarchical".
-I'm trying to use the java.awt.Desktop api to open a text file with the OS's default application.
-The application i'm running is launched from the autorunning jar.
I understand that getting a "file from a file" is not the correct way and that it's called resource. I still can't open it and can't figure out how to do this.
open(new File((this.getClass().getResource("prova.txt")).toURI()));
Is there a way to open the resource with the standard os application from my application?
Thx :)
You'd have to extract the file from the Jar to the temp folder and open that temporary file, much like you would do with files in a Zip-file (which a Jar basically is).
You do not have to extract file to /tmp folder. You can read it directly using `getClass().getResourceAsStream()'. But note that path depend on where your txt file is and what's your class' package. If your txt file is packaged in root of jar use '"/prova.txt"'. (pay attention on leading slash).
I don't think you can open it with external applications. As far as i know, all installers extract their compressed content to a temp location and delete them afterwards.
But you can do it inside your Java code with Class.getResource(String name)
http://download.oracle.com/javase/6/docs/api/java/lang/Class.html#getResource(java.lang.String)
Wrong
open(new File((this.getClass().getResource("prova.txt")).toURI()));
Right
/**
Do you accept the License Agreement of XYZ app.?
*/
import java.awt.Dimension;
import javax.swing.*;
import java.net.URL;
import java.io.File;
import java.io.IOException;
class ShowThyself {
public static void main(String[] args) throws Exception {
// get an URL to a document..
File file = new File("ShowThyself.java");
final URL url = file.toURI().toURL();
// ..then do this
SwingUtilities.invokeLater( new Runnable() {
public void run() {
JEditorPane license = new JEditorPane();
try {
license.setPage(url);
JScrollPane licenseScroll = new JScrollPane(license);
licenseScroll.setPreferredSize(new Dimension(305,90));
int result = JOptionPane.showConfirmDialog(
null,
licenseScroll,
"EULA",
JOptionPane.OK_CANCEL_OPTION);
if (result==JOptionPane.OK_OPTION) {
System.out.println("Install!");
} else {
System.out.println("Maybe later..");
}
} catch(IOException ioe) {
JOptionPane.showMessageDialog(
null,
"Could not read license!");
}
}
});
}
}
There is JarFile and JarEntry classes from JDK. This allows to load a file from JarFile.
JarFile jarFile = new JarFile("jar_file_Name");
JarEntry entry = jarFile.getJarEntry("resource_file_Name_inside_jar");
InputStream stream = jarFile.getInputStream(entry); // this input stream can be used for specific need
If what you're passing to can accept a java.net.URLthis will work:
this.getClass().getResource("prova.txt")).toURI().toURL()

Categories

Resources