简体   繁体   中英

Specifying a relative path in File in Java

I'm uploading images using Spring and Hibernate. I'm saving images on the server as follows.

File savedFile = new File("E:/Project/SpringHibernet/MultiplexTicketBooking/web/images/" + itemName);
item.write(savedFile);

Where itemName is the image file name after parsing the request ( enctype="multipart/form-data" ). I however need to mention the relative path in the constructor of File . Something like the one shown below.

File savedFile = new File("MultiplexTicketBooking/web/images/" + itemName);
item.write(savedFile);

But it doesn't work throwing the FileNotFoundException . Is there a way to specify a relative path with File in Java?

Try printing the working directory from your program.

String curDir = System.getProperty("user.dir");

Gets you that directory. Then check if the directories MultiplexTicketBooking/web/images/ exist in that directory.

Can't count the number of times I've been mistaken about my current dir and spent some time looking for a file I wrote to...

You could get the path of your project using the following -

File file = new File("");
System.out.println("" + file.getAbsolutePath());

So you could have a constants or a properties file where you could define your path which is MultiplexTicketBooking/web/images/ after the relative path.

You could append your path with the path you get from file.getAbsolutePath() and that will be the real path of the file. - file.getAbsolutePath() + MultiplexTicketBooking/web/images/ .

Make sure the folders after the Project path ie MultiplexTicketBooking/web/images/ exist.

It seems the server should offer functionality as might be seen in the methods getContextPath() or getRealPath(String) . It would be common to build paths based on those types of server related and reproducible paths. Do not use something like user.dir which makes almost no sense in a server.

Update

ServletContext sc=request.getSession().getServletContext(); 
File savedFile = new File(sc.getRealPath("images")+"\\" + itemName);

Rather than use "\\\\" I'd tend to replace that with the following which will cause the correct file separator to be used for each platform. Retain cross-platform compatibility for when the client decides to swap the MS/ISS based server out for a Linux/Tomcat stack. ;)

File savedFile = new File(sc.getRealPath("images"), itemName); //note the ','

See File(String,String) for details.

You can specify the path both absolute and relative with File . The FileNotFoundException can be thrown because the folder might be there. Try using the mkdirs() method first in to create the folder structure you need in order to save your file where you're trying to save it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM