0

The following is a servlet that attempts to create a directory and a text file inside that directory.

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    String s = request.getServletContext().getRealPath("/");
    PrintWriter out = response.getWriter();
    FileMaker fm  = new FileMaker();
    fm.makeDirectoryTester();
}

Class that makes a directory and a text file in it :

public void makeDirectoryTester() {
    try {
        File f = new File("FlushTester/");
        if(!f.exists()) {
            boolean b = f.mkdir();
            System.out.println("Directory Made (Inside makeDirectoryTester) --> " + b);
            PrintWriter writer = new PrintWriter("FlushTester/TESTER.txt");
            writer.println("This is the first statement");
            writer.println("This is the second statement");
            writer.println("This is the third statement");
            writer.close();
        }
    }catch(Exception exc) {
        exc.printStackTrace();
    }
}

The problem is that the boolean f.mkdir() returns true but I cannot see any directory created or any file inside it ! Why is that ? I am using tomcat as the server. What could be the reason for this ?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
saplingPro
  • 20,769
  • 53
  • 137
  • 195
  • Where do you expect the file to be created? Which root directory? – Sotirios Delimanolis Jan 30 '13 at 14:17
  • 1
    You keep making the same major mistake. Don't do that. Read the links I posted in your previous related question(s). As to where it's been created, just print `File#getAbsolutePath()`. As to the concrete functional requirement: just stop using `getRealPath()` and relative paths in `File`. On a related note: http://stackoverflow.com/questions/2308188/getresourceasstream-vs-fileinputstream/2308388#2308388 – BalusC Jan 30 '13 at 14:34
  • @BalusC I didn't use `getRealPath()` in my code ! I was testing something and forgot to remove that, in the code I presented here. – saplingPro Jan 30 '13 at 15:55
  • @BalusC with reference to the [question i asked another day](http://stackoverflow.com/questions/14563338/link-doesnt-work-when-i-access-it-via-localhost) is it fine to create directories the way I am creating in the above code so as to download later on ? – saplingPro Jan 30 '13 at 16:01

1 Answers1

1

If you use File f = new File("FlushTester/"); the file is relative to the start point of your application. For tomcat that is usually the bin directory.

If you need it in some other place you should use absolute path (probably configured somehow), or a path relative to your tomcat's bin directory.

jmruc
  • 5,714
  • 3
  • 22
  • 41