Can anyone suggest any ideas how to create a folder in java web application's project structure from code?
Asked
Active
Viewed 6,980 times
2
-
What? please try to explain a bit more what you want to achieve – Lukas Warsitz Oct 24 '13 at 07:31
-
duplicate.... http://stackoverflow.com/questions/3024002/how-to-create-a-folder-in-java – AJ. Oct 24 '13 at 07:31
-
Actually i know how to create a folder in java. But in my java web application, i want to create a folder in the project structure. Also, in that folder i want to create an xml file. This folder should come under the web project structure itself. In a core java application, we can create the folder in the project structure. But in a java web application it is confusing... – Vishnu.K Oct 24 '13 at 07:49
3 Answers
2
You are talking about creating a folder within the servletcontainer/webappContext.. here's how to do it :
public void doPost(HttpServletRequest req,HttpServletResponse resp){
String path = req.getServletContext().getRealPath("/");
File f = new File (path +"myNewFolder");
f.mkdir();
}

Radu Toader
- 1,521
- 16
- 23
-
Our web project have mainly jsp pages and java files. There are no servlet related classes. In this situation, what can we do? – Vishnu.K Oct 24 '13 at 08:44
-
In JSP scriplet code, the implicit object `application` refers to the same Servlet context. So the above code can be written as `<% String path = application.getRealPath("/"); File f = new File (path +"myNewFolder"); f.mkdir(); %>` – jeroen_de_schutter Oct 24 '13 at 09:41
-
See also here : http://stackoverflow.com/questions/2970643/create-a-file-and-store-in-java-web-application-folder?rq=1 – jeroen_de_schutter Oct 24 '13 at 09:58
-
1
Found this :
File f = new File("C:\\Test");
try{
if(f.mkdir()) {
System.out.println("Directory Created");
} else {
System.out.println("Directory is not created");
}
} catch(Exception e){
e.printStackTrace();
}
at How to create a folder in Java?
Hope it helps
-
Here, in the sample provided above, the file 'Test' is saving to C drive. But could you help me how to automatically save a file into a java web project structure (web project in eclipse). – Vishnu.K Oct 24 '13 at 08:40
0
You can do something like this:
String absolute = getClass().getProtectionDomain().getCodeSource().getLocation().toExternalForm();
absolute = absolute.substring(0, absolute.length()-1);
absolute = absolute.substring(0, absolute.lastIndexOf("/")+1);
String xmlPath = absolute + "webapp/xml/";
String os = System.getProperty("os.name");
if(os.indexOf("Windows") != -1) {
xmlPath = xmlPath.replace("/", "\\\\");
if(xmlPath.indexOf("file:\\\\") != -1) {
xmlPath = xmlPath.replace("file:\\\\", "");
}
} else if(xmlPath.indexOf("file:") != -1) {
xmlPath = xmlPath.replace("file:", "");
}
File f = new File(xmlPath);
f.mkdir();

sk2212
- 1,688
- 4
- 23
- 43