Jar file name form java code - java

I would like to determine the jar file name from my java code. I found many solutions in the google, but nothing works. Just to see what I tried here is a stackoverflow forum where a bunch of solutions is posted: stackoverflow
I have Mac OS X 10.6.5.
When I type java -version I get this result:
java version "1.6.0_22"
Java(TM) SE Runtime Environment (build 1.6.0_22-b04-307-10M3261)
Java HotSpot(TM) 64-Bit Server VM (build 17.1-b03-307, mixed mode)
Thank you for your help.
Edit:
I edit my post to answer for the comment.
Some of the solutions gives me "null" value when I want to System.out.println the path and also fails when I want to create an instance of a File.
Other solutions when I ask for the path they don't give something like file:/....., instead they give something like rsch:/ or something like, this I don't know exactly, but it is a 4 character simple word.
Edit 2:
I run an executable jar from the console. And I would like to have this jar file name in the classes which are in the executed jar file.
Edit 3:
The 4 character word is: rsrc:./
Code how I got this:
File file = null;
try {
System.out.println(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
Edit 4:
I also tried this code:
package core;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class MyClass {
public String getText(String key) {
String path = "" + MyClass.class.getResource("../any.properties");
File file = new File((path).substring(5, path.length()));
Properties props = readProps(file);
return props.getProperty(key);
}
private Properties readProps(File file) {
Properties props = new Properties();
InputStream in = null;
try {
in = new FileInputStream(file);
props.load(in);
in.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return props;
}
public static void main(String[] args) {
System.out.println(new MyClass().getText("anything"));
}
}
With this result:
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1937)
at core.PropHandler.getText(MyClass.java:14)
at core.PropHandler.main(MyClass.java:39)
... 5 more
This code perfectly runs in the eclipse, but when I create the runnable jar file I think you can see the problem.

Is this what you want? http://www.uofr.net/~greg/java/get-resource-listing.html
jcomeau#intrepid:/tmp$ cat test.java; javac test.java; jar cvf test.jar test.class; java -cp test.jar test
public class test {
public static void main(String[] args) {
System.out.println(test.class.getResource("test.class"));
}
}
adding: META-INF/ (in=0) (out=0) (stored 0%)
adding: META-INF/MANIFEST.MF (in=56) (out=56) (stored 0%)
adding: test.class (in=845) (out=515) (deflated 39%)
Total:
------
(in = 885) (out = 883) (deflated 0%)
jar:file:/tmp/test.jar!/test.class
For access to resources that works regardless of the presence of a jar file, I always use classname.class.getResourceAsStream(). But the linked document shows how to use JarFile() for the same purpose.

Ok, finally this is the code which resolved my problem:
String sConfigFile = "any.properties";
InputStream in = MyClass.class.getClassLoader().getResourceAsStream(sConfigFile);
if (in == null) {
System.out.println("ugly error handling :D");
}
Properties props = new java.util.Properties();
try {
props.load(in);
} catch (IOException e) {
e.printStackTrace();
}
With this way it founds my property file.

Related

Can't use java.io.* on CodeRunner

import java.io.*;
public class WriteFile {
public static void main(String[] args){
try {
FileWriter writer = new FileWriter("Test.txt");
writer.write("this is a plain text file.\n");
writer.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
错误: 找不到或无法加载主类 O:WriteFile
原因: java.lang.ClassNotFoundException: O:WriteFile
This code can run on both eclipse and vs Code but not on Coderunner. How to solve it.
Your classpath is broken.
Method #1
Try adding the classpath while running it.
On windows:
java -classpath .;yourjar.jar YourMainFile
On Unix:
java -classpath .:yourjar.jar YourMainFile
Method#2
Configure the build path in your IDE and add an external JAR containing your class to the build path.
Method#3
Please read this to resolve the issue.
Note:
You could also refer to this.

URI Schema: Infinite command prompts are opening

I went through the following doc center and tried to create my own URI schema myDocs:
https://msdn.microsoft.com/en-us/library/aa767914(v=vs.85).aspx
Following is my Java program. It takes a command line argument and returns the URL in the browser.
import java.awt.Desktop;
import java.io.IOException;
public class URIOpen {
public static void main(String args[]) {
if (args.length == 0) {
return;
}
String uri = args[0];
try {
Desktop.getDesktop().browse(java.net.URI.create(uri));
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
I updated the (Default) value field of the command key like below.
"C:\Program Files (x86)\Java\jdk1.8.0_102\bin\java" -cp "C:\Users\Krishna\Documents\Study\Miscellaneous\examples" "URIOpen" "%1"
When I try to run the command myDocs:http://google.com, I end up opening infinite command prompts.
The following is my URI schema entry structure in the registry. Any help on this?
Your solution end up opening infinite command prompts because of:
you registered the execution of the custom URIOpen class to be activated by the system when it has to deal with myDocs:'s scheme based URI;
when custom URIOpen class executes the line Desktop.getDesktop().browse(java.net.URI.create(uri)); the system will receive again an URI based on the same scheme ( myDocs: ) and it will activate again a new command to execute your class again and again and again ...
Probably you would like to change your code in someway like that:
try {
java.net.URI theURI = java.net.URI.create(uri);
// System.out.println(theURI.getScheme()); => myDocs
String uriBrowsablePart = theURI.getRawSchemeSpecificPart();
// System.out.println(uriBrowsablePart); => http://google.com
Desktop.getDesktop().browse(java.net.URI.create(uriBrowsablePart));
// the above statement will open default browser on http://google.com
} catch (IOException e) {
System.out.println(e.getMessage());
}
try replacing your try-catch block with my suggestion and see if it works as required.

Project throwing IOException (File Not Found) when jar is run

I've made a project in java, using Eclipse.
Here is the project structure:
When I'm running the project in Eclipse as a java application, it runs perfectly fine.
Now, I need to export it as a jar. So, I created the jar using the method described in 3rd answer on this link (answered by Fever):
Failing to run jar file from command line: “no main manifest attribute”
Here is the output of jar tf EventLogger.jar:
META-INF/MANIFEST.MF
com/
com/project/
com/project/eventLogger/
com/project/eventLogger/KafkaConsumerGroup.class
com/project/eventLogger/KafkaProducer.class
com/project/eventLogger/ConsumeConfig.class
com/project/eventLogger/ConsumerThread.class
com/project/eventLogger/Formatter.class
com/project/eventLogger/Execute.class
com/project/eventLogger/Config.class
com/project/eventLogger/package-info.class
com/project/eventLogger/ProdConfig.class
com/project/eventLogger/FormatConfig.class
resources/
resources/Config.properties
resources/ConsumerConfig.properties
resources/FormatterConfig.properties
resources/ProducerConfig.properties
resources/log4j.properties
Here is the manifest file:
Manifest-Version: 1.0
Built-By: vishrant
Class-Path: lib/json-simple-1.1.1.jar lib/junit-4.10.jar lib/hamcrest-
core-1.1.jar lib/kafka_2.9.2-0.8.2.2.jar lib/jopt-simple-3.2.jar lib/
kafka-clients-0.8.2.2.jar lib/log4j-1.2.16.jar lib/lz4-1.2.0.jar lib/
metrics-core-2.2.0.jar lib/slf4j-api-1.7.6.jar lib/snappy-java-1.1.1.
7.jar lib/slf4j-log4j12-1.6.1.jar lib/zkclient-0.3.jar lib/zookeeper-
3.4.6.jar lib/jline-0.9.94.jar lib/netty-3.7.0.Final.jar lib/scala-li
brary-2.9.2-RC3.jar
Build-Jdk: 1.8.0_74
Created-By: Maven Integration for Eclipse
Main-Class: com.project.eventLogger.Execute
and, here is the exception:
java.io.FileNotFoundException: ConsumerConfig.properties (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at com.project.eventLogger.ConsumeConfig.loadPropertiesFile(ConsumeConfig.java:34)
at com.project.eventLogger.ConsumeConfig.<clinit>(ConsumeConfig.java:42)
at com.project.eventLogger.Execute.main(Execute.java:18)
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.project.eventLogger.Execute.main(Execute.java:18)
Caused by: java.lang.NullPointerException
at com.project.eventLogger.ConsumeConfig.<clinit>(ConsumeConfig.java:47)
... 1 more
Seeing the exception, it is clear that it is not able to load ConsumerConfig.properties which is being done in ConsumeConfig.java.
Here is ConsumeConfig.java:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Properties;
/**
* #author vishrant
*
*/
public class ConsumeConfig {
public static String zookeeper;
public static String balance;
public static String bootstrap_servers;
public static String zk_session_to;
public static String zk_sync;
public static String auto_commit;
public static String[] topics;
private static String kafka_bin;
private static final String PROPERTIES_FILE_PATH = "src/main/resources/ConsumerConfig.properties";
private static Properties loadPropertiesFile() throws IOException {
Properties properties = new Properties();
InputStream in = new FileInputStream(PROPERTIES_FILE_PATH);
properties.load(in);
return properties;
}
static {
Properties property = null;
try {
property = loadPropertiesFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
zookeeper = property.getProperty("ZOOKEEPER");
balance = property.getProperty("BALANCE");
bootstrap_servers = property.getProperty("BOOTSTRAP_SERVERS");
zk_session_to = property.getProperty("ZK_SESSION_TO");
zk_sync = property.getProperty("ZK_SYNC_TIME");
auto_commit = property.getProperty("AUTO_COMMIT_INTERVAL");
topics = property.getProperty("CONSUMER_TOPICS").split(",");
kafka_bin = property.getProperty("KAFKA_BIN_PATH");
}
}
Can someone tell me what is the problem and how to resolve this?
This runs perfectly well when run in Eclipse itself.
EDIT1:
Now, the exception is:
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.project.eventLogger.Execute.main(Execute.java:18)
Caused by: java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:434)
at java.util.Properties.load0(Properties.java:353)
at java.util.Properties.load(Properties.java:341)
at com.project.eventLogger.ConsumeConfig.loadPropertiesFile(ConsumeConfig.java:35)
at com.project.eventLogger.ConsumeConfig.<clinit> (ConsumeConfig.java:42)
... 1 more
line no 35:
props.load(resourceStream);
This is the code now:
private static final String PROPERTIES_FILE_PATH = "ConsumerConfig.properties";
private static Properties loadPropertiesFile() throws IOException {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Properties props = new Properties();
InputStream resourceStream = loader.getResourceAsStream(PROPERTIES_FILE_PATH);
props.load(resourceStream);
return props;
}
I see the following problems to be the cause:
The jar file is not created correctly for a maven project because the directory resources will normally be not copied to the target directory as is, i.e., instead of
resources/Config.properties
it should look like without the resources directory:
Config.properties
directly under the root directory of the jar file.
The second point is you are using the following in your code
private static final String PROPERTIES_FILE_PATH = "src/main/resources/ConsumerConfig.properties";
This path will not be seen outside of your IDE (in this case Eclipse) because src/main/resources should not exist in the jar file as you could see in the list of your jar file.
The last point is, you should use getResourceAsStream() of the class loader as Vikrant Kashyap already pointed.
try this
// Change Your File Path First.
private static final String PROPERTIES_FILE_PATH = "ConsumerConfig.properties";
private static Properties loadPropertiesFile() throws IOException {
Properties properties = new Properties();
// First way to load ResourceAsStream.
// ClassLoader loader = Thread.currentThread().getContextClassLoader();
// InputStream resourceStream = loader.getResourceAsStream(PROPERTIES_FILE_PATH);
// Second way to load ResourceAsStream.
InputStream resourceStream = ConsumeConfig.class.getResourceAsStream(PROPERTIES_FILE_PATH);
properties.load(resourceStream);
return properties;
}

Crawling GitHub with JGit

I'm trying to crawl a GitHub Wiki with JGit.
When I try it with one URL, it worked perfectly fine. Then I tried it with another random URL and got an error.
Please see the extract of my code:
import java.io.File;
import java.io.IOException;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
public class Main {
// with this URL I get an error
String url = "https://github.com/radiant/radiant.wiki.git";
// this URL works
// String url = "https://github.com/WardCunningham/Smallest-Federated-Wiki.wiki.git";
public static void main(String[] args) {
Main m = new Main();
m.jgitTest();
System.out.println("Done!");
}
public void jgitTest() {
try {
File localPath = File.createTempFile("TestGitRepository", "");
localPath.delete();
Git.cloneRepository().setURI(url).setDirectory(localPath).call();
} catch (IOException | GitAPIException e) {
System.err.println("excepton: " + e.getMessage());
e.printStackTrace();
}
}
}
This is the stack trace:
Exception in thread "main" org.eclipse.jgit.dircache.InvalidPathException: Invalid path (contains separator ':'): How-To:-Create-an-Extension.textile
at org.eclipse.jgit.dircache.DirCacheCheckout.checkValidPathSegment(DirCacheCheckout.java:1243)
at org.eclipse.jgit.dircache.DirCacheCheckout.checkValidPathSegment(DirCacheCheckout.java:1225)
at org.eclipse.jgit.dircache.DirCacheCheckout.checkValidPath(DirCacheCheckout.java:1185)
at org.eclipse.jgit.dircache.DirCacheCheckout.processEntry(DirCacheCheckout.java:311)
at org.eclipse.jgit.dircache.DirCacheCheckout.prescanOneTree(DirCacheCheckout.java:290)
at org.eclipse.jgit.dircache.DirCacheCheckout.doCheckout(DirCacheCheckout.java:408)
at org.eclipse.jgit.dircache.DirCacheCheckout.checkout(DirCacheCheckout.java:393)
at org.eclipse.jgit.api.CloneCommand.checkout(CloneCommand.java:236)
at org.eclipse.jgit.api.CloneCommand.call(CloneCommand.java:127)
at Main.jgitTest(Main.java:21)
at Main.main(Main.java:13)
If you visit the wiki page of the URL that doesn't work (https://github.com/radiant/radiant/wiki), you will find this page: How To: Create an Extension.
The title of this page is the cause of the error: Invalid path (contains separator ':'): How-To:-Create-an-Extension.textile.
I assume I need to escape all output.
I suppose you are on windows. You can't create a file on windows having the ":" in the name. JGit should handle it somehow, so I suppose this is a bug in JGit.
I had the same problem with pure git, and this answer helped me:
git config core.protectNTFS false

Extracting Text From JPG

I've tried this code and added the needed jar files but still I'm getting an error message like Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load library 'libtesseract302'.
Is there a complete tutorial how to extract text and what things should be done to address the error? Any help is appreciated...
import net.sourceforge.tess4j.*;
import java.io.File;
public class ExtractTxtFromImg {
public static void main(String[] args) {
File imgFile = new File("C:\\Documents and Settings\\rueca\\Desktop\\sampleImg.jpg");
Tesseract instance = Tesseract.getInstance(); // JNA Interface Mapping
// Tesseract1 instance = new Tesseract1(); // JNA Direct Mapping
try {
String result = instance.doOCR(imgFile);
System.out.println(result);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
In addition to adding the jars, you also need to add the natives. You can do so with Djava.library.path="C:\[absolute path to dir containing *.dll files and such]"
Note that you need to provide the directory, not the file itself.

Categories

Resources