How to write file to ubuntu linux server ? Java 11

Solution for How to write file to ubuntu linux server ? Java 11
is Given Below:

I did deploy java web application writing with spring to ubuntu linux server via Tomcat apache.
I created folder to store all the downloads in the tomcat path inside the linux server folders :
Path : ” opt/tomcat/apache-tomcat-9.0.46/work/downloads/ “

When I try to download file from external API to the ubuntu directory ( Above path )
I get Error 500 external, caused by the server not finding the path.

Method code: ( Java )

@RequestMapping(value = "/downloadDataDump", method = RequestMethod.GET)
public String downloadDataDump(@RequestParam(value = "fileName") String fileName) throws IOException {

    String fileUrl = null;
    URL url = null;
    HttpURLConnection con = null;
    try {
        fileUrl = getHotelDataDumpUrl("all", "en").getBody().getData().getURL();
        url = new URL(fileUrl);
        con = (HttpURLConnection) url.openConnection();
        con.setRequestProperty("Accept-Encoding", "zstd");
    } catch (IOException e) {
        e.printStackTrace();
        } catch (ParseException e) {
        e.printStackTrace();
    }
    FileOutputStream fout = null;
    ZstdInputStream reader = null;
    try {
        reader = new ZstdInputStream(con.getInputStream());
        fout = new FileOutputStream("//212.102.105.18/opt/tomcat/apache-tomcat-9.0.46/work/downloads" + fileName);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

Stack trace (from comment):

java.io.FileNotFoundException: /opt/tomcat/apache-tomcat-9.0.46/work/downloads/hotelNew (Permission denied)
   at java.base/java.io.FileOutputStream.open0(Native Method)
   at java.base/java.io.FileOutputStream.open(FileOutputStream.java:298)
   at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:237)
   at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:126)
   at com.hotels.river.controllers.RateHawkController.downloadDataDump(RateHawkController.java:1068)

You have a permission problem:

  • find out which user is Tomcat running as: it’s the user of the java process,
  • open a shell as Tomcat’s user (let’s say it is tomcat):
    sudo -u tomcat /bin/bash
    
  • try creating a file:
    touch /opt/tomcat/apache-tomcat-9.0.46/work/downloads/hotelNew
    

To create a file Tomcat needs traversal (x) permission to all directories and write (w) permission on the downloads folder.