Load resource file from outside of JAR file - java

With maven I'm building an application which has to load a driver dynamically. With the following code it only works if the driver.so is positioned inside the resulting JAR file. What can I do that the file can be found outside of the JAR within the path ./natives/driver.so.
package com.myproject;
public class Starter {
public static void main(String[] args) {
File classpathRoot = new File(Starter.class.getClassLoader().getResource("driver.so").getPath());
System.out.println(classpathRoot);
}
}
Output when driver is positioned inside JAR is:
jar:file:/home/ted/java/myproject/target/myproject-0.1-SNAPSHOT.jar!/libgdx64.so
Output when positioned outside JAR (in target as well as in target/natives directory) is:
null
I start the application via:
cd /home/ted/java/myproject/target/
java -Djava.library.path=./natives -cp myproject-0.1-SNAPSHOT.jar com.myproject.Starter
What can I do?

Try this:
package com.myproject;
public class Starter {
public static void main(String[] args) {
File file = new File("natives/driver.so");
System.out.println(file);
}
}
or this:
package com.myproject;
public class Starter {
public static void main(String[] args) {
File file = new File(System.getProperty("java.library.path"), "driver.so");
System.out.println(file);
}
}

Related

How to check if file exist after build jlink?

I am trying to check if file exists in project. When I start my application through Intellij idea and check if file exists it's return true but when I create jlink build and start it through .bat and check if file exists it's always return false.
public class App {
public static String getPathToDllTest(String filename) throws URISyntaxException {
return Paths.get(App.class.getResource("files/" + filename + ".txt").toURI()).toString();
}
public static void main(String[] args) throws Exception {
File txt = new File(App.getPathToDllTest("test"));
System.out.println(txt.exists());
}
}
Here is basic Maven project resources structure I use:
src
main
java
com
example
App.java
resources
com
example
files
test.txt
Is there problem in path? How can I fix it?

How to provide java program with external files when executing the run command in console?

So it might seem like a trivial question, but I cannot find any information out there that answers my question. Nonetheless, it is a very general coding question.
Suppose you have a java program that reads a file and creates a data structure based on the information provided by the file. So you do:
javac javaprogram.java
java javaprogram
Easy enough, but what I want to do here is to provide the program with a file specified in the command line, like this:
javac javaprogram.java
java javaprogram -file
What code do I have to write to conclude this very concern?
Thanks.
One of the best command-line utility libraries for Java out there is JCommander.
A trivial implementation based on your thread description would be:
public class javaprogram {
#Parameter(names={"-file"})
String filePath;
public static void main(String[] args) {
// instantiate your main class
javaprogram program = new javaprogram();
// intialize JCommander and parse input arguments
JCommander.newBuilder().addObject(program).build().parse(args);
// use your file path which is now accessible through the 'filePath' field
}
}
You should make sure that the library jar is available under your classpath when compiling the javaprogram.java class file.
Otherwise, in case you don't need an utility around you program argument, you may keep the program entry simple enough reading the file path as a raw program argument:
public class javaprogram {
private static final String FILE_SWITCH = "-file";
public static void main(String[] args) {
if ((args.length == 2) && (FILE_SWITCH.equals(args[0]))) {
final String filePath = args[1];
// use your file path which is now accessible through the 'filePath' local variable
}
}
}
The easiest way to do it is using -D, so if you have some file, you could call
java -Dmy.file=file.txt javaprogram
And inside you program you could read it with System.getProperty("my.file").
public class Main {
public static void main(String[] args) {
String filename = System.getProperty("my.file");
if (filename == null) {
System.exit(-1); // Or wharever you want
}
// Read and process your file
}
}
Or you could use third a party tool like picocli
import java.io.File;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
#Command(name = "Sample", header = "%n#|green Sample demo|#")
public class Sample implements Runnable {
#Option(names = {"-f", "--file"}, required = true, description = "Filename")
private File file;
#Override
public void run() {
System.out.printf("Loading %s%n", file.getAbsolutePath());
}
public static void main(String[] args) {
CommandLine.run(new Sample(), System.err, args);
}
}
You can pass file path as argument in two ways:
1)
public class Main {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("File path plz");
return;
}
System.out.println("File path: " + args[0]);
}
}
2) Use JCommander
Let's go step by step. First you need to pass the file path to your program.
Lets say you execute your program like this:
java javaprogram /foo/bar/file.txt
Strings that come after "javaprogram" will be passed as arguments to your program. This is the reason behind the syntax of the main method:
public static void main(String[] args) {
//args is the array that would store all the values passed when executing your program
String filePath = args[0]; //filePath will contain /foo/bar/file.txt
}
Now that you were able to get a the file path and name from the command-line, you need to open and read your file.
Take a look at File class and FileInputStream class.
https://www.mkyong.com/java/how-to-read-file-in-java-fileinputstream/
That should get you started.
Good luck!

How to get path to class file in eclipse and linux in java?

In eclipse for windows, when I run
public class HelloWorld {
public static void main(String[] args) {
System.out.println(System.getProperty("user.dir"));
}
}
It gives me the path of the project root folder (which contains the bin folder which has the class file). For example
SampleProject
and the class file is actually located at
SampleProject\bin\myclass.class
But if I run the same program in linux with
javac myclass.java
java myclass
it gives me the directory that has the .class file, which is the same as pwd command. This is what I want in eclipse for windows. I want some code that will give me the path to the class file in both eclipse for windows and linux.
Does anyone know how do this?
Thanks
If I understand you correctly, you'd like a method that retrieves a class' path on disk. This is easily achievable, like so:
public String getClassPath(Class c) {
try {
return c.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
NOTE this will work even if the class is contained in a jar file. It will return the path to the jar in this case.
The easiest way is to do this:
public class HelloWorld {
public static void main(String[] args) {
System.out.println(HelloWorld.class.getResource("HelloWorld.class"));
}
}

Runtime Error: Main method not found in class ImageTool, please define the main method as: public static void main(String[] args)

Why does my code (compiles fine) gives me the following error?
Main method not found in class ImageTool, please define the main method as: public static void main(String[] args)
Code:
public class ImageTool {
public static void main(String[] args) {
if (args.length <1) {
System.out.println("Please type in an argument");
System.exit(-1);
}
if (args[0].equals("--dump")) {
String filename = args[1];
int[][] image = readGrayscaleImage(filename);
print2DArray(image);
} else if (args[0].equals("--reflectV")) {
String filename = args[1];
int[][] image = readGrayscaleImage(filename);
int[][] reflect = reflectV(image); //reflectV method must be written
String outputFilename = args[2];
writeGrayscaleImage(outputFilename,reflect);
}
}
Your main method looks fine.
1) Probably your .class file does not correspond to your .java file.
I would try to clean up my project (if I was using an IDE and getting this).
That is: delete the .class file, regenerate it from the .java file.
2) Seems you're not running ImageFile but some other class,
even though you think you're running ImageFile. Check what
your IDE is running behind the scenes.
I hope one of these two suggestions would help.

Eclipse Plugin Get Code from Current Open File

How can I get the code from the current open file in Eclipse returned in a String or String[]? I need this for a plugin I'm making.
Let's say I have the following code:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
If I have HelloWorld.java open, how do I get that code returned in a String[]? The String[] would contain:
"public class HelloWorld {"
"public static void main(String[] args) {"
"System.out.println("Hello, world!");"
"}"
"}"
To get the currently edited file's content you can do something like that:
IWorkbenchPart workbenchPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart();
IFile file = (IFile) workbenchPart.getSite().getPage().getActiveEditor().getEditorInput().getAdapter(IFile.class);
if (file == null) throw new FileNotFoundException();
String content = IOUtils.toString(file.getContents(), file.getCharset());

Categories

Resources