I am working on an Eclipse Web Dynamic Project, and trying to access a file that exists in my local machine/server.
What I am looking for is something like "base_url()" in CodeIgniter, which automatically points to the directory the server is located.
I am using a Mac.
try{
model.read(new FileInputStream(url),"");
}catch(IOException e)
{
System.out.println("Exception caught"+e.getMessage());
}
This is the part of the code I am working on, which I am trying to feed the correct URL path to read.
After searching StackOverflow and other places, I came across this piece of code:
String url = request.getRequestURL().toString().replace(request.getRequestURI().substring(1), request.getContextPath())
+"/WebContent/WEB-INF/test.xml";
Which did not seem to work.
I then tried to hard code the path directory in, only to realise that I dont know how Mac file systems work :/
Can anyone share some light on this?
Thank you in advance
I did not understand very well if you are using a servlet or something else (like a WS), however the request object exposes a method called getRealPath() which gives well... the real path of the servlet's context in your file system.
So you need to change your code with this:
String url = this.getServletContext().getRealPath("")+"/test.xml";
It has nothing to do with OS, as you surely know java is portable.
I think what you want is
String path = getServletContext().getRealPath("/");
which point to the bas directory of your application in the server
e.g. /opt/tomcat/webapps/MyApp
I always use getResourceAsStream and suck it up off of my class path. Flat file names are problematic inside of web applications.
Related
I am trying to create a folder within web server using Java File handling APIs in my RESTFul web service developed using JERSEY.
According to my understanding, when I target "xyz.com" , it by default points out /home/xyz/public_html/ in my server.
So when I try to create a folder as follows
String appFolderPath = "/xyz.com/appFolder/";
File userNameFolder = new File(appFolderPath + userName);
if (!userNameFolder.exists()) {
folderPath = userNameFolder.mkdir();
}
The above code fails, I am not getting any exception, and no folder is created.
How exactly I suppose to do it ? How to give path for public_html/ folder ?
Another point is, is it not happening because of permission issue ? , I actually tried another way , I manually created /appFolder under public_html/ and give full read write permission to that folder, but still I couldn't create any folder within that using above code.
Please let me know how to achieve it ? Any Sample code ?
Also if possible let me know if JERSEY does give me APIs to make it simple ?
To point to public web directory use
ServletContext context = request.getServletContext();
String path = context.getRealPath("/");
and append your path to the path (above resolved)
According to my understanding, when I target "xyz.com" , it by default points out /home/xyz/public_html/ in my server.
What makes you think so? You're operating files in the code snippet given, so your path means /xyz.com/appFolder/ and nothing more. And it's very likely you're facing a permission issue trying to create folders like this.
As for absense of exception, that's a design feature of Java file API not to throw exceptions on certain failures, but rather return erroneous error codes. Check what is returned by mkdir() call and you'll find false there, as a signal of failure.
I'm having trouble with simply counting the number of files stored on one of my directories on a server.
I'm an Android beginner and I know I must be making a simple mistake with my code
File file = null;
try {
file = new File(new URI("http://myURL/directory/userImages/"));
}
catch (URISyntaxException e) {
e.printStackTrace();
}
Log.d(TAG, "Num of Files: " + file.list().length);
I'm getting a URI exception:
Expected file scheme in URI: http://myURL/directory/userImages/
I can't seem to find out the problem here. It's obviously a problem with the URI.
Any help or info would be greatly appreciated. Thanks in advance
This won't work as the URI constructor of the File class that you are using only works with file URIs as documented in the JDK. Concretely this means that your URI has the start with "file://", which in itself means that you can only access local files (or files on remote systems mounted as local drives on your system).
I'm not sure what the exact context is of this particular piece of code, but I'm pretty sure that what you are trying to achieve will need some more complex code.
Particularly, as far as I now, it is not possible to fetch a directory via HTTP. I think you might need FTP/SSH/... access to the particular system to solve this.
If you give some more context, I (or others) might be able to give some more help.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Not possible to launch a file on a network using Java Desktop?
I am trying to use the Desktop API to launch the appropriate app for a file. So i am using this :
if (Desktop.isDesktopSupported())
Desktop.getDesktop().open(new File(path));
where "path" is a String pointing to the file.
Everything works fine until i try to launch a jpg that resides at a network location (for instance "\\MyNet\folder\image.jpg") when i get an IOException :
java.io.IOException: Failed to open
file:////MyNet/folder/image.jpg
Any one knows if there is a way to fix this?
I believe you need to specify the file location/name in standard URI format - which is close to the standard format except for servers. See the javadocs for the URI Class for more information.
At the highest level a URI reference (hereinafter simply "URI") in string form has the syntax
[scheme:]scheme-specific-part[#fragment]
And a little later:
A hierarchical URI is subject to further parsing according to the syntax
[scheme:][//authority][path][?query][#fragment]
so the URI should look something like the following:
file://MyNet/folder/image.jpg
where "file://" is the protocol, "MyNet" is the server, and "/folder/image.jpg" is the directory location under the share.
Hope this helps a little.
file:////MyNet/folder/image.jpg is not a file path. It's an URL.
File f = new File("\\\\192.168.0.4\\mybookrw\\save\\command.txt");
Desktop.getDesktop().open(f);
Worked fine for me. The one caveat is that you have to be authenticated against the share already. If you paste the path into the run box and it prompts you for a username and password then its not going to work from an app.
Everyone so far has assumed that the file isn't being found.
However, looking at the Desktop open() function, an IOException is thrown
if the specified file has no associated
application or the associated
application fails to be launched
Now, having said that, what happens if you open a jpg on your local machine? Also, what happens if you try manually launching the jpg through the network?
Edit: Actually, the problem may be that the default program set to open jpg files doesn't understand file:// uris. Sticking with UNC paths might be a better choice.
This problem has been bugging me for a while. I have to load a couple files in my java app, and the only way I got working so far looks like this:
URL hsURL;
if(System.getProperty("os.name").toLowerCase().contains("windows")) {
hsURL = new URL("file:/" + System.getProperty("user.dir") + "/helpsets/helpset.hs");
}
else {
hsURL = new URL("file://" + System.getProperty("user.dir") + "/helpsets/helpset.hs");
}
But this is ugly and terrible. For a while I thought I had this working:
hsURL = ClassLoader.getSystemResource("helpsets/helpset.hs");
But that no longer works for some reason (I must have changed something and not noticed. It returns null.
Should I be using getResource() instead of getSystemResource() (if so, why is getSystemResource() static but not getResource())?
I am using eclipse and I have tried including the folder in the build path (classpath) and not including it, it doesn't seem to make a difference.
getSystemResource is static because it will use the system classloader, which is available statically. (ClassLoader.getSystemClassLoader)
If your resource is available in the classpath, I would suggest using ClassLoader.getResource() or Class.getResource from an appropriate class, e.g.
Foo.class.getResource("/helpsets/helpset.hs");
(ClassLoader.getResource is "absolute"; Class.getResource is relative to the package of the class unless you prefix it with a '/'.)
If this doesn't work, please post how your app is configured in terms of the classpath, and where your file is.
EDIT: I usually find the URL less useful than an InputStream, so I use getResourceAsStream instead of getResource. YMMV
You've mentioned several different things here, so let's sort them out.
1) Creating a "file:" URL based on "user.dir"
The "user.dir" property refers to the current working directory -- wherever the user might have been when s/he started the app. Chances are good that files written here will disappear between two runs (because the user might run from a different directory).
The "user.home" property refers to the user's home directory -- which should remain the same between runs.
In either case, use a File object to open files, don't muck around with creating a "file:" URL. You get no benefit, and as you can see, you have to write messy code to access it.
2) Retrieving a resource via the classloader
This is meant to retrieve files that are packaged with your application -- read-only files. As you have seen, there are multiple variants. I prefer using the following, because I assume that a class will want to load a file that's packaged with it.
InputStream in = this.getClass().getClassLoader().getResourceAsStream(fileName);
I'm new to Java. I'm simply trying to build a .jar file of my applet so I can run it from my browser. This is what my directory structure looks like:
C:\java\pacman\src
contains all of the .java class files.
C:\java\pacman\assets
contains about 4-5 images and audio files.
If I try to use the following code:
Image someFile=getCodeBase().toString() + "file.png";
The result of getCodeBase() is
file:/C:/java/pacman/bin/
However the following code fails to load:
img=new ImgHelper(getCodeBase().toString() + "assets/");
ImageIO.read(new File(img.getPath("pacman.png")));
Moving my 'assets' folder to the 'bin' folder didn't fix this either. It tries loading:
file:/C:/java/pacman/bin/assets/pacman.png
saying:
Can't read input file!
But the url it gave opens fine if I paste it into run and hit enter:
So to avoid myself a lot of headache i commented out the code in my ImgHelper class and did this:
public ImgHelper(String dir)
{
//this.imgDir=dir;
imgDir="C:\\java\\pacman\\assets\\";
}
Which works perfectly. But I want to put this on a web server, and I have no idea how/what I should do to make all the images and sounds work. Any ideas?
Thanks...
Why not put it all in a JAR file and then call Class.getResourceAsStream?
A JAR file is better as it is a single HTTP connection rather than one HTTP connection per file. It is also much more flexible to use a Stream than a File.
getResourceAsStream will work when the files are not in a JAR as well, they need to be relative to the class file.
EDIT:
Another thing, the File method won't work if the applet is on a server as it will be trying to open the file from the local machine (I think, I haven't tried it) rather then from the server. Even if it tried to create a file path to the server that won't work.
I agree with tofubeer about the JAR, but if you want to put the image on your server, see the tutorial on Applet images here. The codebase will be whatever location your applet is on the server, and you can put images relative to that on the server as well. Use a media tracker along with the Applet.getImage() method to retrive the url. From the example:
my_gif = getImage(getDocumentBase(),"imageExample.gif");
There are two possible solutions that would work:
The images could be present outside the applet JAR. The applet could then be initialized with the location of the directory where the images are present. Once you have that information you could then load images from the server. The Sun Java tutorial provides an example usage of the applet parameter to pass the image source directory.
The applet class loader could be utilized to load the images from the applet's JAR, using the getResourceAsStream() method.
PS: It would be helpful if you referred to the section in the Java tutorials to load icons for your application. The same section discusses a lot of the points brought forth by TofuBeer and John.
EDIT : The usage of the File API is not recommended because it ends up reading off the local file system. That is unacceptable for most users on the internet.