将文件保存到Java中不存在的路径



我正在创建一个简单的客户机/服务器应用程序,它允许服务器从客户机接收文件。在这个应用程序中,如果文件在给定的基本路径内,客户端还可以决定将文件存储在服务器文件系统的何处。

问题是,如果客户端发送一个路径,服务器创建,即,这个字符串作为路径:C:basePathnewFolderfile.xml。如果当前文件系统中不存在newFolder,则抛出以下错误:

Error: C:remtServerprovat.xml (Access denied)

还有这两个错误,但我认为它们是无关的,因为它们源自第一个错误:

[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.

我不是很有经验的Java,所以可能是一个微不足道的问题,但我不能弄清楚。

这是服务器中的代码:

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

由于目录不存在而发生错误。如何创建目录来解决这个问题?否则,我怎么解它?

在服务器端,下面的代码将创建所有目录(假设在服务器端运行的Java具有必要的文件权限)

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

最新更新