I have the following code in a static class called Methods that is archived in a jar:
System.out.println(Methods.class.getResource("tagdict.txt")); // 1
URL test = Methods.class.getResource("tagdict.txt"); // 2
System.out.println(test.getPath()); // 3
TagDictionary dict = new POSDictionary(test.getPath()); // 4
The first System.out (1) says:
rsrc:de/fhg/scai/bio/harsha/classificationworkflow/tagdict.txt
The second System.out (2) says:
de/fhg/scai/bio/harsha/classificationworkflow/tagdict.txt
Line 4 throws a
java.io.FileNotFoundException: de/fhg/scai/bio/harsha/classificationworkflow/tagdict.txt (No such file or directory)
The file tagdict.txt is placed in the same package as the Method.class, which is de/fhg/scai/bio/harsha/classificationworkflow.
I do not understand why line 4 throws a FileNotFoundException even though the file was found already inside the jar.
Line 3 just prints out the path component of the URL returned by getResource. It doesn't actually check if that path represents a real file on disk.
It looks like the POSDictionary constructor is trying to create a File using the path string passed to it, and this path doesn't actually represent an on-disk file, therefore throwing the exception.
I do not understand why line 4 throws a FileNotFoundException even though the file was found already inside the jar.
Because if the resource is in a JAR, then it's not a file. Such resources can only be accessed by opening input streams directly from the URL object, or by using getResourceAsStream() instead of getResource(). They can't be accessed using java.io.File, since they're not actual disk files.
Related
I have a text file in my resource folder and I need to be able to read/remove/add text. I believe I have to use append so I tried this.
Files.write(Paths.get(Testing.class.getResource("/testresources/SearchList.txt").getPath())
, "the text".getBytes(), StandardOpenOption.APPEND);
This gives me back
Exception in thread "main" java.nio.file.InvalidPathException: Illegal char <:> at index 2: /C:/Users/Ben/workspace/Eve/bin/org/me/Testing/resources/SearchList.txt
If anyone could should me some clarity on this subject that would be great. Thankyou!
This worked for me fine:
You should add the text file to a raw folder. If the raw folder does not exist in your resource directory, create one. And then in order to access it and write or edit it, use this:
OutputStream outputStream=getResources().openRawResource(R.raw.YourTextFile);
then in order to Read from the file, you should do this
InputStream inputStream=getResources().openRawResource(R.raw.YourTextFile);
A leading slash is being automatically added to your path - /C:/Users/Ben/workspace/Eve/bin/org/me/Testing/resources/SearchList.txt
Lots of solutions have been suggested here in answers, Java NIO file path issue
Use any of those mentioned answers as your solution.
Also, for files intended to be in jar, You need to use Paths method public static Path get(URI uri) instead of public static Path get(String first,String... more) See How to get a path to a resource in a Java JAR file
I have this code
Files.delete(Paths.get("a.txt"));
FileWriter f = new FileWriter("a.txt");
First line will delete file,
second line will create file but when i checked file created date it will give old one.
It is not because you declare a new instance of FileWriter that the underlying file is affected or even created in any ways.
According to the Javadoc, the constructor will throw an IOException in these cases (java 7)
IOException - if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason
Try writing something in your file.
Also, you should be consistent and use Paths.get either in both statements or not at all. AFAIK Paths.get is filesystem dependent (in other words you may not be deleting the file that you are trying to recreate).
New to Java. I am building a Java HTTP server (no special libraries allowed). There are certain files I need to serve (templates is what I call them) and I was serving them up using this piece of code:
this.getClass().getResourceAsStream("/http/templates/404.html")
And including them in my .jar. This was working. (I realize I was reading them as an input stream.)
Now I want to store all of my files (as File type) for templates, regular files, redirects in a hashmap that looks like this: url -> file. The I have a Response class that serves up the files.
This works for everything except my templates. If I try to insert the getResource code in the hashmap, I get an error in my Response class.
This is my code that I am using to build my hashmap:
new File(this.getClass().getResource("/http/templates/404.html").getFile())
This is the error I'm getting:
Exception in thread "main" java.io.FileNotFoundException: file:/Users/Kelly/Desktop/Java_HTTP_Server/build/jar/server.jar!/http/templates/404.html (No such file or directory)
I ran this command and can see the templates in my jar:
jar tf server.jar
Where is my thinking going wrong? I think I'm missing a piece to the puzzle.
UPDATE: Here's a slice of what I get when I run the last command above...so I think I have the path to the file correctly?
http/server/serverSocket/SystemServerSocket.class
http/server/serverSocket/WebServerSocket.class
http/server/ServerTest.class
http/templates/
http/templates/404.html
http/templates/file_directory.html
http/templates/form.html
The FileNotFoundException error you are getting is not from this line:
new File(this.getClass().getResource("/http/templates/404.html").getFile())
It appears that after you are storing these File objects in hash map, you are trying to read the file (or serve the file by reading using FileInputStream or related APIs). It would have been more useful if you had given the stack trace and the code which is actually throwing this exception.
But the point is that files present within the JAR files are not the same as files on disk. In particular, a File object represents an abstract path name on disk and all standard libraries using File object assume that it is accessible. So /a/path/like/this is a valid abstract path name, but file:/Users/Kelly/Desktop/Java_HTTP_Server/build/jar/server.jar!/http/templates/404.html is not. This is exactly what you get when you call getResource("/http/templates/404.html").getFile(). It just returns a string representing something that doesn't exist as a file on disk.
There are two ways you can serve resources from class path directly:
Directly return the stream as a response to the request. this.getClass().getResourceAsStream() will return you the InputStream object which you can then return to the caller. This will require you to store an InputStream object in your hash map instead of a file. You can have two hash maps one for files from class path and one for files on disk.
Extract all the templates (possibly on first access) to a temporary location say /tmp and then store the File object representing the newly extracted file.
I am trying to understand "How to get to file by passing relative path of a file or folder?" . Here is the example:
CODE:
public class somex {
public static void main {
String fileName = System.getProperty("user.dir"); <---This gives me path for the current working directory.
File file = new File(fileName + "../../xml_tutorial/sample.xlsx" );
System.out.println(file.getCanonicalPath()); <---This gives me path for the file that is residing in folder called "xml_tutorial".
}
}
>>>>
Here, I know the file location so i was able to pass correct relative path. And, managed to print the file path. I have deleted the "sample.xlsx" and executed the above code; With no failing it gives me the path name and it is same path as when the file exists (i.e. before deleting). How it is possible ? I am expecting EXCEPTION here. why it is not throwing exception ?
Two, I want to use regular expression for the file name, such as: "../../xml_tutorial/samp.*". But this doesn't do the job and it gives me IOException. Why it is not able to identify the file sample.xlsx ? (NOTE: this is when the file exist and one hundred precent sure there is only one file with the name "sample.xlsx")
I have deleted the "sample.xlsx" and executed the above code; With no failing it gives me the path name and it is same path as when the file exists (i.e. before deleting). How it is possible ? I am expecting EXCEPTION here. why it is not throwing exception ?
File doesn't care whether the file actually exists. It just resolves the path. There's no need for the file to exist in order to take the path
/home/tjc/a/b/c/../../file.txt
...and turn it into the canonical form
/home/tjc/a/file.txt
If you want to know whether the file on that path actually exists, you can use the exists() method.
On your second, unrelated question:
Two, I want to use regular expression for the file name, such as: "../../xml_tutorial/samp.*". But this doesn't do the job and it gives me IOException. Why it is not able to identify the file sample.xlsx ?
There's nothing in the File documentation saying that it supports wildcards. If you want to do searches, you'll want to use list(FilenameFilter) or listFiles(FilenameFilter) and a FilenameFilter implementation, or listFiles(FileFilter) and a FileFilter implementation.
A program we have erred when trying to move files from one directory to another. After much debugging I located the error by writing a small utility program that just moves a file from one directory to another (code below). It turns out that while moving files around on the local filesystem works fine, trying to move a file to another filesystem fails.
Why is this? The question might be platform specific - we are running Linux on ext3, if that matters.
And the second question; should I have been using something else than the renameTo() method of the File class? It seems as if this just works on local filesystems.
Tests (run as root):
touch /tmp/test/afile
java FileMover /tmp/test/afile /root/
The file move was successful
touch /tmp/test/afile
java FileMover /tmp/test/afile /some_other_disk/
The file move was erroneous
Code:
import java.io.File;
public class FileMover {
public static void main(String arguments[] ) throws Exception {
boolean success;
File file = new File(arguments[0]);
File destinationDir = new File(arguments[1]);
File destinationFile = new File(destinationDir,file.getName() );
success = file.renameTo(destinationFile);
System.out.println("The file move was " + (success?"successful":"erroneous"));
}
}
Java 7 and above
Use Files.move(Path source, Path target, CopyOption... opts).
Note that you must not provide the ATOMIC_MOVE option when moving files between file systems.
Java 6 and below
From the docs of File.renameTo:
[...] The rename operation might not be able to move a file from one filesystem to another [...]
The obvious workaround would be to copy the file "manually" by opening a new file, write the content to the file, and delete the old file.
You could also try the FileUtils.moveFile method from Apache Commons.
Javadoc to the rescue:
Many aspects of the behavior of this method are inherently
platform-dependent: The rename operation might not be able to move a
file from one filesystem to another, it might not be atomic, and it
might not succeed if a file with the destination abstract pathname
already exists. The return value should always be checked to make sure
that the rename operation was successful.
Note that the Files class defines the move method to move or rename a
file in a platform independent manner.
From the docs:
Renames the file denoted by this abstract pathname.
Many aspects of the behavior of this method are inherently
platform-dependent: The rename operation might not be able to move a
file from one filesystem to another, it might not be atomic, and it
might not succeed if a file with the destination abstract pathname
already exists. The return value should always be checked to make sure
that the rename operation was successful.
If you want to move file between different file system you can use Apache's moveFile
your ider is error
beause /some_other_disk/ is relative url but completely url ,can not find the url
i have example
java FileMover D:\Eclipse33_workspace_j2ee\test\src\a\a.txt D:\Eclipse33_workspace_j2ee\test\src
The file move was successful
java FileMover D:\Eclipse33_workspace_j2ee\test\src\a\a.txt \Eclipse33_workspace_j2ee\test\src
The file move was erronous
result is url is error