How to add path to file in Java args - java

i am working on one project and i come to the problem.
I need to run .jar over cmnd prompt and i need to put path to .properties file into the argument, for example:
java -jar myproject.jar C:\path\to\config.properties
Now i have a path to file satatic
FileInputStream in = new FileInputStream("config\\crdb.properties");
And i need to somehow put variable instead of static path and change it with argument.
Thank you.

use -D to put your System variable and use System.getProperty to get it :
java -Dpath.properties=C:\path\to\config.properties -jar myproject.jar
String pathProp= System.getProperty("path.properties");
FileInputStream in = new FileInputStream(pathProp);

Simply use args array:
public static void main(String args[]) {
try (FileInputStream in = new FileInputStream(args[0])) {
// do stuff..
}
}

if you are reading the property file from main method you can simply access command line arguments via args[] array public static void main(String args[]) simple code like below might do
public static void main(String[] args) {
String splitChar="=";
try {
Map<String, String> propertyList = Files.readAllLines(Paths.get(args[0]))
.stream()
.map(String.class::cast)
.collect(Collectors.toMap(line -> line.split(splitChar)[0],
line -> line.split(splitChar)[1]));
System.out.println(propertyList);
} catch (IOException e) {
e.printStackTrace();
}
}
or else you can pass the path as vm option
java -Dfile.path={path to config file} {JavaClassFile to execute}
and you can get the path like below (from any where in your code)
System.getProperty("file.path")
and same as in main method above you can read the property file and put it into a HashMap which I prefer

Related

Pass multiple specific files as one string arg from another java program

I am trying to pass few specific paths as a string arg in one program to call another java program. I get an ArrayIndexOutOfBoundsException error but when I pass the exact same arg in the command line it works perfectly
What is doable in command line:
program1 /filepath/{A,B,C}/*.zip
What I want to do that is giving me an error:
program2 [call program 1]:
status = ToolRunner.run(conf, program1, new String[]{"/filepath/{A,B,C}/*.zip"});
I am not sure how I can pass it that way, even if I want to pass all the paths and change the second program I am not sure how can I aggregate all the paths and assign it as input stream.
I appreciate your help,
Thank you :)
ToolRunner.run() method receives as arguments:
A Configuration object
A Tool object
A String array of arguments to be passed to the Tool object
Is your "program1" an object extending the Tool interface? Attending to the name you used, it seems it is more a refence to some "binary" or executable thing...
Please, have a look to the documentation.
ToolRunner is typically used in Hadoop applications as:
public final class MyMRClass extends Configured implements Tool {
...
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(new Configuration(), new MyMRClass(), args);
System.exit(res);
} // main
#Override
public int run(String[] args) throws Exception {
Configuration conf = this.getConf();
Job job = Job.getInstance(conf, "some job name");
...
}
}

Xtend how to get full path of current working directory

I have written a grammar that allows the user to input a relative path. (e.g. "../../temp/out/path"
May aim is to get the absolute path based on the input from the user, and the absolute path of the current working directory so that I can also check if the input path is valid or not.
Is there libraries or built in functions that I can use to get the absolute path?
Something similar to C's _getcwd() function.
Yes, Java has a File class. You can create one by calling this constructor which takes a String. Then you can call getAbsolutePath() on it. You can call it like this:
package com.sandbox;
import java.io.File;
public class Sandbox {
public static void main(String[] args) {
File file = new File("relative path");
String absolutePathString = file.getAbsolutePath();
}
}
This will print a complete absolute path from where your application has initialized.
public class JavaApplication1 {
public static void main(String[] args) {
System.out.println("Working Directory = " +System.getProperty("user.dir"));
}
}

passing values into another java project via runtime.exec()

Here is my code to invoke a java project from another java project
package pkgtry;
import java.io.*;
public class Try
{
private static void runProcess(String command) throws Exception
{
Process pro = Runtime.getRuntime().exec(command);
pro.waitFor();
InputStream inputStream = pro.getInputStream();
int b = -1;
while ( (b = inputStream.read()) != -1 )
{
System.out.write(b);
}
}
public static void main(String[] args)
{
int x=10;
try
{
runProcess("javac -d . C:\\Users\\owner\\Documents\\NetBeansProjects\\input\\src\\input\\Input.java");
runProcess("java input.Input");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
This code is working perfectly. What i want is to pass an variable say 'x' from Try.java to Input.java
i would like to know the what all changes are to be made in Try.java to send the parameter and in Input.java to receive the parameter. Thanks in advance
You need to append it to command and in Input.java in main method you will have this value stored in args parameter.
Everything you want to pass to the called program is added to its commandline, like this
runProcess("java input.Input All Parameters You Want To Pass");
In Input.java you can retrieve these parameters by reading out String[] args, like this:
public class Input {
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
}
will produce
All
Parameters
You
Want
To
Pass
But you should know that this is a rather heavy-handed way to make one piece of Java code call some other piece of Java code, you can add the jar produced by the project containing Input to the Try project and instantiate the Input class directly. Calling via the command line is slow and cumbersome, and severely limits the communication between the two classes (command line parameters in one direction, an integer return value in the other direction.

Java: How to determine startup arguments without the main line access?

I'm curious to know if it is possible to determine the startup arguments of a Java application when you don't have access to the arguments array from the main line.
public static void main(String[] args)
{
// Invokes my code without providing arguments.
mycode();
}
public static void mycode()
{
// Attempting to determine arguments here.
// TODO GetArgs()
}
I'm in this situation by doing some plugin work and the core application does not provide a list of startup arguments. Any thoughts?
Not unless the plugin is given them, but that kind of goes without saying (at least in Java).
If you need to set some options specifically for your plugin, but can't access the command line, there are at least two options:
Options file (several mechanisms)
Set system params on the command line
For the second option, just use the normal -D option and namespace the param name, like:
java -Dcom.davelnewton.plugins.foo.bar=anOptionValue etc...
Retrieve them via System.getProperty(anOptionName) or one of its cousins.
IMO an options file is a better (ahem) option, even if you're specifying the file path on the command line, but if you only have an option or two, maybe not--just depends.
Pass the arguments to the function?
public static void main(String[] args)
{
mycode(args);
}
public static void mycode(String[] args)
{
String arg1 = args[0];
}
You could do:
public static void main(String[] args)
{
System.setProperty("cmdArgs", args);
mycode();
}
public static void mycode()
{
// Attempting to determine arguments here.
String[] args = System.getProperty("cmdArgs");
}

How to get getclass().getResource() from a static context?

I have a function where I am trying to load a file to a URL object, because the example project said so.
public class SecureFTP {
public static void main(String[] args) throws IOException , ClassNotFoundException, SQLException , JSchException, SftpException{
File file = new File("/home/xxxxx/.ssh/authorized_keys");
URL keyFileURL = this.getClass().getClassLoader().getResource(file);
I tried using SecureFTP.class.getResource, but it still could not compile it.
I am fairly new to Java, so I know I am doing something wrong.
The main method is a static method, so trying to access this (= the current Object) will not work.
You can replace that line by
URL keyFileURL = SecureFTP.class.getClassLoader().getResource("/home/xxxxx/.ssh/authorized_keys");
From: How to call getClass() from a static method in Java?
Just use TheClassName.class instead of getClass().
Old question but this hasn't been said yet. You can do this from a static context:
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
classLoader.getResource("filename");
It can't compile because getResource takes a resource name (a String, and not a File) as parameter, in order to load a resource using the class loading mechanism (from the classpath). Using it with a File makes no sense. If you want to open a file, just use a FileInputStream or a FileReader.
See http://docs.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html#getResource%28java.lang.String%29, and include the compiler error message next time you have such a question.
SecureFTP.class.getClassLoader().getResource(<<your resource name>>);
Should do the trick!
Do it this way so that it works EITHER from a static method or an instance method:
public static String loadTestFile(String fileName) {
File file = FileUtils.getFile("src", "test", "resources", fileName);
try {
return FileUtils.readFileToString(file, StandardCharsets.UTF_8);
} catch (IOException e) {
log.error("Error loading test file: " + fileName, e);
return StringUtils.EMPTY;
}
}

Categories