problem in reading xml file from jar [duplicate] - java

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
file not found exception in jar
hi
I have one class
and in that i have one file
Document doc = db.parse(element.xml);
but when i create jar it is not getting loaded,
so please tell me is there any other way to give path for file,
so i can run my jar

Use class loader to load any resource from class path:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("/com/ensarm/niidle/web/social/sites/sitelist.xml");
db.parse(input);

db.parse(Foo.class.getResource("/com/ensarm/niidle/web/social/sites/sitelist.xml").toString());
Where Foo is the class in which you are writing this code which is in the same jar

Call getResourceAsStream and read the data from the stream:
db.parse(Foo.class.getResourceAsStream("/com/ensarm/niidle/web/social/sites/sitelist.xml"));
You should always prefer to use streams to read the data rather than expecting there to be a particular file.

User ClassLoader.getSystemResource("root/src/com/ensarm/niidle/web/social/sites/sitelist.xml").getPath(); to point to xml's or any resource files..
Note : You must add xml file location to Classpath . (-Djava.class.path="C:\project\resources" ) where xml's are present at C:\project\resources

ClassLoader loadClass = Thread.currentThread().getContextClassLoader() ;
InputStream in =
new InputStreamReader(loadClass.getResourceAsStream("com/ensarm/niidle/web/social/sites/sitelist.xml") );

Related

gwt servlet getRessourceAsStream always returns null [duplicate]

This question already has answers here:
getResourceAsStream returns null
(26 answers)
Closed 6 years ago.
I have this peace of code to load a text file inside of a servlet:
String lFileName = mServletContext.getRealPath(mFile);
InputStream lInputStream = mServletContext.getResourceAsStream(lFileName);
InputStream lInputStream2 = mServletContext.getResourceAsStream(mFile);
Both InputStream's are null. I have absolutly no idear why.
The value of mFile is "file.txt".
The value of lFile is "C:\development\workspace\MyGwtApp\war\file.txt".
if I navigate with my explorer to that directory the file file.txt is in it...!
I test my gwt application with the super dev mode.
Compile the gwt app runs without problems.
Do you see the problem?
getResourceAsStream definition
Finds a resource with a given name. The rules for searching resources associated with a given class are implemented by the defining class loader of the class. This method delegates to this object's class loader.
This means that you can read mFile if it exists in your classpath like under WEB-INF/classes. So place your file in your src directory where your java classes exists and look if the file comes to the classes directory and just use its name to get it as resource. Example: filename = "file.txt"

Extract resource folder from running jar in Java 7

My resources folder inside my jar includes a directory with several binary files. I am attempting to use this code to extract them:
try(InputStream is = ExternalHTMLThumbnail.class.getResourceAsStream("/wkhtmltoimage")) {
Files.copy(is, Paths.get("/home/dan/wkhtmltoimage");
}
This is throwing the error
java.nio.file.NoSuchFileException: /home/dan/wkhtmltoimage
Which comes from
if (errno() == UnixConstants.ENOENT)
return new NoSuchFileException(file, other, null);
in UnixException.java. Even though in Files.java the correct options are passed:
ostream = newOutputStream(target, StandardOpenOption.CREATE_NEW,
StandardOpenOption.WRITE);
from Files.copy. Of course there's not! That's why I'm trying to make it. I don't yet understand Path and Files enough to do this right. What's the best way to extract the directory and all its contents?
Confused because the docs for Files.copy claims
By default, the copy fails if the target file already exists or is a symbolic link
(Apparently it fails if the target file doesn't exist as well?)
And lists the possible exceptions, and NoSuchFileException is not one of them.
If you're using Guava:
URL url = Resources.getResource(ExternalHTMLThumbnail.class, "wkhtmltoimage");
byte[] bytes = Resources.toByteArray(url);
Files.write(bytes, new File("/my/path/myFile"));
You could of course just chain that all into one line; I declared the variables to make it more readable.
The file that does not exist may actually be the directory you're trying to create the file in.
/home/dan/wkhtmltoimage
Does /home/dan exist? Probably not if you're on a Mac.

InputStream from jar-File returns always null

i know this question has been asked several times, but i think my problem differs a bit from the others:
String resourcePath = "/Path/To/Resource.jar";
File newFile = new File(resourcePath);
InputStream in1 = this.getClass().getResourceAsStream(resourcePath);
InputStream in2 = this.getClass().getClassLoader().getResourceAsStream(resourcePath);
The File-Object newFile is completely fine (the .jar file has been found and you can get its meta-data like newFile.length() etc)
On the other hand the InputStream always return null.
I know the javadoc says that the getResourceAsStream() is null if there is no resource found with this name, but the File is there! (obviously, because it's in the File-Object)
Anyone know why this happens and how i can fix it so that i can get the .jar File in the InputStream?
The getResourceAsStream() method doesn't load a file from the file system; it loads a resource from the classpath. You can use it to load, for example, a property file that's packaged inside your JAR. You cannot use it to load a file from the file system.
So, if your file resides on the file system, rather than in your JAR file, better use the FileInputStream class.

How to automatically create a missing folder? [duplicate]

This question already has answers here:
Method in Java to create a file at a location, creating directories if necessary?
(3 answers)
Closed 1 year ago.
In java, I need to write a string into a new file, like 'c:\test\upload\myfile.txt', if the 'upload' folder is not existing, it will automatically create it. how to do it ? Apache Commons IO has this API ?
File file = new File(...);
file.mkdirs(); //for several levels, without the "s" for one level
FileWriter fileWriter = new FileWriter(file);
fileWriter.write("...");
Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.
Returns:
true if and only if the directory was created, along with all necessary parent directories; false otherwise
See File.mkdirs() and File.mkdir()
In addition to the accepted answer, since the question also mentioned the library Apache Common IO, I report in the following a solution by using this nice library:
File file = new File("... the directory path ...");
FileUtils.forceMkdir(file);
This solution uses the class FileUtils, from package org.apache.commons.io and the method forceMkdir, that "Makes a directory, including any necessary but nonexistent parent directories".
new File(fileToSave.getParent()).mkdirs();
It returns a boolean to check if the making succeeded (will fail if the disk is full or if a file exists with the name 'upload', etc)

Problem with Java FileReader [duplicate]

This question already has answers here:
FileNotFoundException, the file exists Java [closed]
(2 answers)
Closed 7 years ago.
Hello I have this in my code
File file = new File("words.txt");
Scanner scanFile = new Scanner(new FileReader(file));
ArrayList<String> words = new ArrayList<String>();
String theWord;
while (scanFile.hasNext()){
theWord = scanFile.next();
words.add(theWord);
}
But for some reason I am getting a
java.io.FileNotFoundException
I have the words.txt file in the same folder as all of my .java files
What am I doing wrong? Thanks!
Tip: add this line to your code...
System.out.println(file.getAbsolutePath());
Then compare that path with where your file actually is. The problem should be immediately obvious.
The file should reside in the directory from which you execute the application, i.e. the working directory.
Generally it's a good idea to package data files with your code, but then using java.io.File to read them is a problem, as it's hard to find them. The solution is to use the getResource() methods in java.lang.ClassLoader to open a stream to a file. That way the ClassLoader looks for your files in the location where your code is stored, wherever that may be.
try:
URL url = this.getClass().getResource( "words.txt" );
File file = new File(url.getPath());
You haven't specified an absolute path. The path would therefore be treated as a path, relative to the current working directory of the process. Usually this is the directory from where you've launched the Main-Class.
If you're unsure about the location of the working directory, you can print it out using the following snippet:
System.out.println(System.getProperty("user.dir"));
Fixing the problem will require adding the necessary directories in the original path, to locate the file.

Categories