Not able to get files under directory in web application(java) - java

step1
I am using the following code to get files under scripts directory
File directory = new File("scripts");
File[] dirlist = directory.listFiles();
It is working fine in stand alone application but when i build this application as jar and place it lib folder of another web application it is giving null pointer exception. It was trying to pickup the folder from eclipse source folder location(C:\softwares\eclipse-jee-luna-R-win32\eclipse\scripts). I am trying to solve this from couple of days but no luck. If any help appriciated.
Thanks

You can try with this code
ServletContext application = getServletContext();
String fullPath = application.getRealPath("");
fullPath = fullPath + "/scripts/";
File directory = new File(fullPath);

Eclipse won't be there when you deploy to the production server. You'll have to move or copy the scripts into the webapp, as resources. Then, use ServletContext.getRealPath() to get the real path to "scripts", convert that to a File, and then proceed as per your second line.

Related

How to find the path of a file local eclipse project

I have created a .txt file in my Eclipse Java project, and I want to find out the path to it so I can use it for a Scanner. I do not want to find out the path on my local drive, as I will be planning to share the program to someone else, and they will have a different folder structure, rather a path that can be used on anybodies machine.
Here is the code:
this.file = new File("<insert path here>");
you can use :
= new File("Build Path"); (your .java file exist in your build path)
The build path is used for building your application. It contains all of your source files and all Java libraries that are required to compile the application.
In eclipse, the default behavior is for the Java system property user.dir to be set to the project directory. This is what dictates where the "root" of File operations is. So if you created a file test.txt in the root project directory, you should be able to access it with new File("test.txt").
However, as Andrew Thompson mentioned in his comment, the more correct method would be using embedded resources.
Try one of These:
1.
System.getProperty("user.dir");
2.
File currentDirFile = new File(".");
String helper = currentDirFile.getAbsolutePath();
String currentDir = helper.substring(0, helper.length() - currentDirFile.getCanonicalPath().length());//this line may need a try-catch
I have not tested it just found while googling

How to locate and execute a file with java

I am making a game with java as kind of a side project and am still new to the language. I was wondering how I could run a file when i didn't know the complete path, like if I were to send the game to a friend, and he has a different path location than me.
Thank you in advance for any help.
code I am currently using:
File file = new File("/Users/(my name)/Desktop/script1.vbs");
Desktop desktop = Desktop.getDesktop();
if(file.exists()) desktop.open(file);`
You could place the file (script1.vbs) in the project folder, that way the path would always be like this...
File file = new File("script1.vbs")
Place the file, not in the src or bin folder, but in the root folder.
Instead of
File file = new File("/Users/(my name)/Desktop/script1.vbs");
you should better use
File file = new File(System.getProperty("user.home"), "Desktop/script1.vbs");
See also the list of System Properties
Or you can use this, to locate your file in the resources folder:
File file = new File("classpath:com/company/script1.vbs");
"classpath:Route Of Source folders/Name and extension of the file"

Listing files in project directory in Linux environment using File.listFiles() in java

String path = ".";
String files="";
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
System.out.println("files::::::::::::"+files);
}
}
Say the above java file I saved under the path D:/spike/FileList.java.
In the above code if I run in windows platform, it will list the files under the 'spike' directory.
But when I keep this in Linux environment say the path is usr/local/apache/webapps/webtest/src/FileList.java
The result I get is files under root directory.
What I require is under the project root folder, i.e. in above case under the webtest directory.
How can I do the same. My requirement is I need to first list the files and then from the list of files I need to read sample.properties file.
I know we can hard code the path to get the same. But without hard coding how can I get the list of files under the project root folder of webapps i.e, under webtest folder in my case.
I also tried by reading the environmental variables. But the problem here is my apache folder owner is spike and not root. So when I execute System.getenv() what I get is only whatever variables the user spike has set.
But when I execute System.getenv() from any other folder whose owner is root, then I get the complete environmental variables.
So is there any way I can get the project root folder by using the above java code snippet without hard coding the path?
By the way this is a web application deployed in tomcat. First the app will read the details from the server.properties file. But Im not supposed to hard code the path as the path changes from system to system. So my intention is that the code read the properties file from the project starting folder.
This is not true, your code on Linux
prints the files in the current folder.
I just tried it.
As to tomcat, see here
What determines the current working directory of Tomcat Java process?
and/or look for similar information on the Tomcat site.
If your file sample.properties is located in the root folder, and actually is a properties-file I would try this loading the file and printing the content:
String filename = "sample.properties";
Properties properties = new Properties();
properties.load(getClass().getClassLoader().getResource(filename).openStream());
properties.list(System.out);
getClass.getClassLoader() will get the location of the rootfolder. If you skip getClassLoader you will get the folder of the package in your class.
(If you are running this in a standalone java app the properties file needs to be located in the classes folder.)
You can try with the current working directory:
String path = System.getProperty("user.dir");
But this depends where exactly is the CWD, e.g. how was this application started?
In the context of a web application, you can do (as long as you have the ServletContext object):
ServletContext application = ...
String path = application.getRealPath("/");
This will give you the root of the web application, you can navigate to the required directory from there.

File upload to the server directory

I am uploading an excel file to the tomcat server. Which is saving inside my eclipse directory D:\workspace_Eclipse\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\StatusPortal\Job_doc\abc.xls
When ever i am accessing this file its giving me file not found Exception \Job_doc\abc.xls.
Its could not able to find the path which is i am giving while accessing the file like
\Job_doc\abc.xls
I am giving the path \Job_doc\abc.xls while accessing.
This is because you are using a relative path. Eclipse will use the current working directory to be a temp location for deploying the webapp. So the file is uploaded to the folder relative to this path (This happens when you start the app from eclipse Run On Server. Define your paths as static constants(May be you can use absolute paths for testing). After testing you can use the relative paths on production deployment.
Still, you can do alternate way. Dont use the integrated tomcat server of Eclipse. Use a standalone server, use the descriptor file to link the webapp in workspace to tomcat. After the save, just reload the app in tomcat manager and try.
Try reading your file using ClassLoader as below:
InputStream inputStream =
getClass().getClassLoader().getResourceAsStream("/Job_doc/abc.xls");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream ));
If you want to get the File object, then try as below:
URI uri = getClass().getClassLoader().getResource("/Job_doc/abc.xls").toURI();
File file = new File(uri);

Load a File in a JSF application

My logic need to load a File that is embedded in the applications .war.
The file is located at the root of the application. It works fine on my machine
because the path is hard coded: File hmmFile = new File("/home/kirill/projetos/biosearchrefinement/pos-en-bio-medpost.HiddenMarkovModel");
but when I deploy it to a server it won`t work because the absolute path is different.
I tried to use ClassLoader but got a null reference and tried to use FacesContext but no success either. I am using glassfish 3 and Mojarra 2.1.6
My project tree looks like this:
In my code I am referencing the file like this:
File hmmFile = new File("/home/kirill/projetos/biosearchrefinement/pos-en-bio-medpost.HiddenMarkovModel");
But this only works when I run the application locally, if I deploy it to a remote server obviously it will stop loading that File. I would like to load this file Relatively to the project`s root folder.
Thanks!
From your vague description, what you need is to use the Class.getResourceAsStream() method.
Solved the problem using getRealPath() from ExternalContext.
ExternalContext ext = FacesContext.getCurrentInstance().getExternalContext();
String resourcesPath = ext.getRealPath("/WEB-INF/resources");
File hmmFile = new File(resourcesPath + "/pos-en-bio-medpost.HiddenMarkovModel");
Worked fine!

Categories

Resources