-1

enter image description here
My project has the following directories in Java Web Netbeans. I create a file and i want to save it inside the dist folder .
I tried using

FileOutputStream(".\\dist\\file.pdf"))

But i get can not locate path. If i use the whole path including '''C:// so on"" it works but it is not efficient if i specify it as the project would not be able to run in different machines.

What can I do for it ?

  • If you are creating a Web application, then your directory structure would be packaged in a [WAR](https://en.wikipedia.org/wiki/WAR_(file_format)) file, correct? – Abra Apr 23 '21 at 05:20
  • I think so when i display an image i just put src="images/image1.png" – user15520720 Apr 23 '21 at 06:00
  • You should have a look at this link: [What does servletcontext.getRealPath(“/”) mean and when should I use it](https://stackoverflow.com/a/12160863/14868118) – oktaykcr Apr 23 '21 at 13:46

1 Answers1

0

I don't know if it is the best way, but I did it in another project like this:

StringBuilder sb; 
FileOutputStream fos;
sb = new StringBuilder("");

// to get project root:
sb.append(new java.io.File(".").getCanonicalPath());

// File.separator for system specific file separator:
sb.append(File.separator);

sb.append("dist");
sb.append(File.separator);
sb.append("file.pdf");

fos = new FileOutputStream(sb.toString());

As I said, I don't know if this is the best way, but for me it worked.

  • This is an extremely long way to write the equivalent of either `new File("dist", "file.pdf")` or `Path.of("dist", "file.pdf")`. – DuncG Apr 23 '21 at 16:12
  • @DuncG: That's a good one! I will change that in my project. I think the StringBuilder way is still valid for building paths. The example above is a simple one, you alread got the path and just need to add the filename. – SprintFriend Apr 24 '21 at 13:23