Load a file from a specific directory - java

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"));
}
}

Related

how to save created file to path specified in application.properties file in spring boot

I have a method which creates new file after every execution I don't want to hardcode file path in code so I added a new property in application.properties file like
jmeter.jmx.path=D:\\PerformanceTesting\\JMXFiles\\
and instance variable which holds value like
#Value("${jmeter.jmx.path}")
private String jmxPath;
want to get the value of a variable inside method
public void saveAsJmxFile(HashTree projectTree, String fileName) throws IOException {
//TODO
SaveService.saveTree(projectTree, new FileOutputStream(jmxPath+fileName+".jmx"));
}
its not woking for me, but if i hardcode then it i'll work.
public void saveAsJmxFile(HashTree projectTree, String fileName) throws IOException {
//TODO remove hardcoded jmxPath
SaveService.saveTree(projectTree, new
FileOutputStream("D:\\PerformanceTesting\\JMXFiles\\"+fileName+".jmx"));
}
just make sure that the directory is exist
Files.createDirectories(Paths.get(jmxPath));
i'm using java8+ nio here

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.

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);

getClass().getResource() in static context

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")

Reading From Config File Outside Jar Java

Currently I am trying to read my config file from root of project directory, in order to make this actual configuration I want to move this to external location and then read from there.
Adding a complete path in following code throws out error :
package CopyEJ;
import java.util.Properties;
public class Config
{
Properties configFile;
public Config()
{
configFile = new java.util.Properties();
try {
// configFile.load(this.getClass().getClassLoader().getResourceAsStream("CopyEJ/config.properties"));
Error Statement ** configFile.load(this.getClass().getClassLoader().getResourceAsStream("C://EJ_Service//config.properties"));
}catch(Exception eta){
eta.printStackTrace();
}
}
public String getProperty(String key)
{
String value = this.configFile.getProperty(key);
return value;
}
}
Here's the error:
java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:365)
at java.util.Properties.load(Properties.java:293)
at CopyEJ.Config.<init>(Config.java:13)
at CopyEJ.CopyEJ.main(CopyEJ.java:22)
Exception in thread "main" java.lang.NullPointerException
at java.io.File.<init>(File.java:194)
at CopyEJ.CopyEJ.main(CopyEJ.java:48)
How can I fix this ?
The purpose of method getResourceAsStream is to open stream on some file, which exists inside your jar. If you know exact location of particular file, just open new FileInputStream.
I.e. your code should look like:
try (FileInputStream fis = new FileInputStream("C://EJ_Service//config.properties")) {
configFile.load(fis);
} catch(Exception eta){
eta.printStackTrace();
}
This line requires your config.properties to be in the java CLASSPATH
this.getClass().getClassLoader().getResourceAsStream("C://EJ_Service//config.properties")
When it is not, config.properties won't be accessible.
You can try some other alternative and use the configFile.load() function to read from.
One example would be:
InputStream inputStream = new FileInputStream(new File("C:/EJ_Service/config.properties"));
configFile.load(inputStream);

Categories

Resources