我正在創建一個簡單的客戶端/服務器應用程式,讓服務器從客戶端接收檔案。在此應用程式中,客戶端還可以決定將檔案存盤在服務器檔案系統中的哪個位置,如果它位于給定的基本路徑中。
問題是如果客戶端發送一個路徑,服務器創建,即這個字串作為路徑:C:\basePath\newFolder\file.xml。如果newFolder當前檔案系統中不存在,則會拋出此錯誤:
Error: C:\remtServer\prova\t.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
發生錯誤是因為目錄不存在。如何創建目錄來解決這個問題?否則,我該如何解決?
uj5u.com熱心網友回復:
在服務器端,下面的代碼用make所有的目錄(假設運行在服務器端的Java有必要的檔案權限)
File f = ...; // The file path the client has submitted
File dir = null;
if (f.isFile()) {
dir = f.getParentFile();
} else dir = f;
dir.mkdirs();
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/471935.html
