Home > Mobile >  Saving a file in non-existent path in Java
Saving a file in non-existent path in Java

Time:05-06

I am creating a simple client/server application that lets the server receive a file from the client. In this application, the client could also decide where to store the file in the server's file system, if it is inside a given base path.

The problem is that if the client sends a path, the server creates, ie, this string as path : C:\basePath\newFolder\file.xml. If the newFolder does not exsist in the current file system, it throws this error:

Error: C:\remtServer\prova\t.xml (Access denied)

And also these two errors, but I think they are irrelevant, because they derive from the first one:

[Fatal Error] :1:8: XML document structures must start and end within the same entity.
Error: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 8; XML document structures must start and end within the same entity.

I am not very experienced in Java, so maybe it is a trivial matter, but I can't figure out.

This is the code in the server:

public static void receive(String token, String fileName, String filePath, int length) throws IOException{

        // Stream for binary data and file transfer
        OutputStream out = new FileOutputStream(basePath   filePath   fileName);
        InputStream in = socket.getInputStream();

        // Variables 
        int bytesRead;

        // Bytes for store info to be sent
        byte[] buffer = new byte[length];

        //-------------------------
        // Send file 
        //------------------------- 

        while((bytesRead = in.read(buffer)) > 0){
            out.write(buffer, 0, bytesRead);

            if (bytesRead < 1024) {
                break;
            }

        } // while

        //-------------------------
        // End of file transfer
        //-------------------------
        

        out.close();
    } // receive

The error occurs because the directory does not exist. How can I create the directory to fix that? Otherwise, how can I solve that?

CodePudding user response:

On the server side, the following code with make all the directories (assuming that the Java running on the server side has the necessary file permissions)

File f = ...; // The file path the client has submitted
File dir = null;
if (f.isFile()) {
  dir = f.getParentFile();
} else dir = f;
dir.mkdirs();
  • Related