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")'‘
Related
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"));
}
}
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
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.
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")
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()