In my application, i got an function where i need to write a file inside webcontent folder, i got a folder called data and i need to write a new name, if i gave the real path( C:\Users\SanWin\workspace\RoleAccessControl\data\ActivityLog.txt) it writes the file but this has to change when the project is to run on different machine, so i used this to get the real path
ServletContext ctx = getServletContext();
String path = ctx.getRealPath("/data/ActivityLog.txt");
System.out.println(path);
when i print i got the following message in console
C:\Users\SanWin\workspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\RoleAccessControl\data\ActivityLog.txt
i dont know how the system gets this line
.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\
this is in eclipse, i was expecting something like
C:\Users\SanWin\workspace\RoleAccessControl\data\ActivityLog.txt
how to get the real path i want to get rid of the lines (.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps), I looked and did all possible i seen in internet, but failed, sorry if I made an duplicate post,kindly excuse me
Thanks for your time and responses
In the Servers view in Eclipse you can double click your server to open a configuration screen which allows you to set a different deploy path (at least in Tomcat). Note that you can only modify that setting when there is nothing deployed, otherwise you will see the options grayed out.
The .metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ you are getting is because you have the Use workspace metadata option.
Anyway, if you deploy your war manually directly into Tomcat webapps folder, without Eclipse, you will be getting the correct path.
In other words, your code is correct and is giving you the correct path, you are just not liking the path where your app is being deployed.
Hope this helps.
Related
For some unusual reason, when I am using FileWriter for Java Netbean, the file gets written into this directory:
C:\Users\myname\AppData\Roaming\NetBeans\7.2\config\GF3\domain1
rather than to my working directory, which is at the desktop.
I used this code to check my User Directory, and it returns this:
System.out.println(System.getProperty("user.dir"));
INFO: C:\Users\myname\AppData\Roaming\NetBeans\7.2\config\GF3\domain1
which is obviously NOT my working directory where my source code is. I thought I could have accidentally configured Netbeans to change the directory, but I checked through NetBeans menu and can't figure out how to undo this.
I have never had this problem before in my previous projects. As simple as the following code, the file should appear in my working directory.
File file = new File("myFile.xml");
Instead now I'm being forced to enter the path name to make the file save into my working directory, which is not going to be dynamic if I change computer.
String dir = "C:\\Users\\myname\\Desktop\\Assignment\\IRAssignmentJ\\";
File file = new File(dir + "myFile.xml");
Please enlighten me how do I solve this.
rather than to my working directory, which is at the desktop
No it isn't. The current working directory is whereever the file got saved, by definition. If Netbeans chooses to change directory to where it was saved, there's nothing you can do about it. If you want it in your home directory, there is a system property for that. If you want it saved somewhere else, use a full pathname.
But the behaviour of the application under Netbeans is of little interest. What matters is when you run it as though standalone, like a customer would.
I have created a dynamic web project, and use Apache Tomcat as a server.
In my servlet I'm creating a text file and want to reuse that in a JSP. However they are by default created in the installation folder of Eclipse when I do something as simple as the following:
File f = new file("test.txt").
I don't know why this happens. Is there a way to create the file in the WebContent directory as I want to make that file available for download in my JSP.
Java has a concept of the "current directory". When you start an application via Eclipse, this may indeed point to your installation directory. If you don't specify any path, a file will be created in this current directory. Hence the reason why your test.txt ends up there.
The WebContent directory is a something that is specific to Eclipse. Your code should not depend on putting anything there. You only start your application via Eclipse when you're developing it, not when you're deploying it to a live server.
The content of this directory will become the root of your .war, which is a well known location independent of how you start & deploy you app, BUT you still cannot depend on writing anything to this location at run-time. You might deploy your application as a packaged .war (likely for live deployments) or you may deploy your application unpackaged but then your application server may simply not pick up any changes done at run-time.
What you can do if you are sure your application only runs on a single server is writing the files to a well known location on your file system, such as /tmp, or /var/yourapp/files, etc. The code serving up those files can then pick them up from that location.
If you want to play it 100% safe according to the Java EE rules, you'd store your files on something like an FTP server that has a configurable address. Technically your war could be shipped between nodes on a cluster and requests could end up going to different machines, so depending on a local filesystem wouldn't work then.
Executing this statement this.getServletContext().getRealPath (""), you'll obtain the path where Tomcat WebServer is pointing at at runtime. You could add a folder "MyFolder" and call this statement:
new File(this.getServletContext().getRealPath ("") + "/MyFolder/test.txt");
Anyway, the default path looks something like:
...\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\<NameOfYourProject>
Note that when you create a new file, it won't appear in your immediate workspace (check the .metadata path), unless you change the runtime location tomcat should point at.
I want to implement an upload component in my servlet file,but it doesn't work.
The code episode seems like follows:
SmartUpload smartUpload=new SmartUpload();
StringBuffer stringBuffer=new StringBuffer();
smartUpload.initialize(config,request, response);
try {
smartUpload.upload();
File file=smartUpload.getFiles().getFile(0);
stringBuffer.append(file.getFileName());
file.saveAs("/upload_resources/"+stringBuffer);
} catch (SmartUploadException e) {
e.printStackTrace();
}
The upload_resource directory is just under the WebRoot directory,the code runs without any errors ,but the file is just not uploaded. By the way , even I changed the line
file.saveAs("/upload_resources/"+stringBuffer);
to
file.saveAs(request.getRealPath("/upload_resources/")+"/"+stringBuffer);
that is to use an absolute path, the file is not uploaded.
Any help will be appreciate. Thanks.
I've never really worked with SmartUpload, but I can tell that you shouldn't be saving uploaded files in the webapp's deploy folder. They may all get lost whenever the webapp get redeployed with the simple reason that the uploaded files are not contained in the original WAR file. So you should not prepare the upload folder in the webapp's deploy folder, but on a fixed path outside the deploy folder.
If SmartUpload is well designed, I'd expect that
file.saveAs("/upload_resources/"+stringBuffer);
will save it to the /uploaded_resources folder on the root of the same disk as where the webserver is started from. So in for example Windows that would be C:\uploaded_resources. Prepare and use that folder instead.
Further there's another potential problem when you're using the MSIE browser. This browser namely incorrectly includes the full client side path in the filename. I'm not sure if SmartUpload handles this properly, but you might want to debug the actual value of file.getFileName() and make sure that it's really only the filename in the form of filename.ext. Otherwise, you'd need to use String#substring() to substring the part after the last / and \.
I'm trying to read from a text file in Netbeans. In the top level of my project directory I have foo.txt. Then in my code I have:
File file = new File("foo.txt");
It throws a FileNotFoundException, however. It's a Java web application using Spring and Tomcat, but I'm not sure if those details matter since I'm running the whole thing inside Netbeans. Basically, I just want to know where I need to put the file so Netbeans will read it.
Update - good call guys, it's looking in Tomcat's bin directory. Now this may be a stupid question but, how would I go about getting it to look in my top level project directory? I feel like dropping text files into tomcat's bin would be innapropriate.
You can try printing the absolute path of the File object to see where it is looking on the filesystem.
System.out.println(file.getAbsolutePath());
I would use the following to figure out where to put the file:
System.out.println(System.getProperty("user.dir"));
To directly answer your question, If you're running an application on Tomcat, files will be opened from the current working directory. That will likely be the bin/ folder in your tomcat directory.
You can find out for sure where your program is looking by examining the result of file.getAbsolutePath().
However, for web applications, I would suggest putting files you need to read in your classpath so you don't have to depend on a certain file structure when you deploy your web application.
try System.getProperty("user.dir") to get current working directory
I try to read a .txt file line by line in my code, which I placed it just right under the /src/ directory, when I run it with test case or with static void main, the path output is correct. However, when I run the application with Tomcat server, the app root path points to where I download my Eclipse - D:\eclipse\..., while the correct path should be D:\workspace\myproject\src\. Then, of course, it can never find the file.
Below is my code:
String workDir = System.getProperty("user.dir");
String file = "numFile.txt";
File myFile = new File(workDir + file);
String userPath = myFile.getPath();
So, my questions are:
(this maybe dumb) Where should we normally place a text file?
How can I change [System.getProperty("user.dir");], so it will point to my project workspace?
Thank you!
Sharon
regarding to your reply:
add following arguments -Duser.home='Your Path' make sure you add -D at the begining of your system variable. And this variable you can put in the VM Arguments box provided under arguments tab when you Open the Launch Configuration when using tomcat server.
I cannot find the place you are talking about. Is it in Eclipse or Tomcat directory?
thanks
Try File myFile = new File(workDir, file);
The short answer is that you can't change a running application's current working directory in Java; see Changing the current working directory in Java?
Setting the user.dir property won't work, because that doesn't affect the actual current directory that the OS uses when resolving pathnames for the application.
Setting the -Duser.dir on the command line won't work either. Rather, you have to:
if you are launching using a script, cd to the relevant directory before running the application,
if you are launching using a ProcessBuilder, set the working directory using the directory(File) method, or
if you are using an Eclipse launcher, set the "Working Directory" in the launch configuration.
Finally, what you are trying to do is (IMO) a bad idea:
Some folks write Tomcat and webapp config files on the assumption that Tomcat's current directory is the default location; e.g. $CATALINA_HOME/bin. (This is wrong ... but your hack will break it.)
When your application goes into production, you won't want to be referring back to some development sandbox.
A better approach is to do something along the lines of #Eng.Fouad's answer.
OK! I got it!
Yes,
File myFile = new File(workDir + "/" + file);
is the way to go.
and I edit the tomcat argument in Eclipse IDE. (Run -> Run Config... -> Apache Tomcat -> [Click] Tomcat vX Server -> at the right screen, click "Argument" -> Working directory section -> I change to Other and specify my actual working directory.)
It's just wierd that even I run tomcat Not by eclipse IDE, but Dos cmd and even deploy to server, it still apply the working directory as D:\Eclipse. But change the working directory worked anyway.
To read files from the root of the classpath use (eclipse automatically copies any non java file from src to classes):
this.getClass().getClassLoader().getResourceAsStream("filename.txt");
So you don't have to mess with the current folder at all.
try not to change the system properties, instead, add one more parameter into the system properties.
For Eg. add following arguments -Duser.home='Your Path' make sure you add -D at the begining of your system variable. And this variable you can put in the VM Arguments box provided under arguments tab when you Open the Launch Configuration when using tomcat server.
And if you are runing the same from some main method, then add the vairable in the run configuration, as this will maintain sactity in you code.