2015-10-28 23 views
0

我想在Java中使用DatagramPackets發送片段中的文件(部分是assignemt)。當我試圖保存傳入文件時,我得到訪問被拒絕的錯誤,但我相信它是不是權限問題。 它的首當其衝:在Java中保存通過DatagramPackets接收到的文件

我讓用戶發送文件來使用FileChooser來選擇它。並創建一個新的消息對象。

//.... 
File f = content.showFileChooser(); 
      byte type = Byte.parseByte("4"); 
      Message m; 
      try { 
       if (mode == 1){ 
        m = new Message(f, content.getServerData().getFragmentSize(), (short) (sentMessages.size()+1), type); 
        serverThread.send(m); 
       } 
//... 

在消息創建過程中,文件被分割成字節數組,每個數組的大小由用戶預先確定。該代碼是相當漫長的,所以我不打算髮布斬波處理,但這是我如何轉換的文件對象變成然後把它切碎了

Path p = Paths.get(file.getAbsolutePath()); 
    this.rawData = Files.readAllBytes(p); 

創建消息後,切碎大的byte []上傳到字節數組中,我使用DatagramPackets發送它們。另一方然後使用這些來創建一個新的消息對象。一旦所有碎片到達rawData再次從Message對象中提取。這個問題相信就在這裏:

  Message m = receivedMessages.get(msgIndex-1); 
      byte[] fileData = m.getFile(); 
      if (fileData != null){ 
       System.out.println("All file fragments received."); 
       content.append("Received a file in" + m.getFragmentCount()+" fragments. Choose directory. " ,1); 
       //I BELIEVE THIS TO BE THE CRITICAL POINT 
       String filePath = content.chooseDirectory(); 
       if (filePath == null) 
        return; 
       FileOutputStream fos; 
       try { 
        fos = new FileOutputStream(filePath); 
        fos.write(fileData); 
        fos.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 

一旦所有碎片到達我讓用戶選擇使用文件選擇與DIRECTORY_ONLY選擇模式的目錄。據我所知,FileOutputStream需要一個完整的路徑爲新的文件。我是否需要單獨發送文件名和擴展名,還是可以從接收的文件數據中提取?

+0

'FuleOutputStream'不需要完整路徑。看到Javadoc。不清楚你在問什麼。 – EJP

回答

1

您正在編寫目錄路徑爲filePath,然後嘗試打開該目錄FileOutputStream。難怪這不行,你必須指定文件名。

String filename = "myfile.txt"; //Or receive and set this some other way 
File outFile = new File(filePath, filename); 
fos = new FileOutputStream(outFile); 

儘管如此,我沒有看到你發送/接收文件名。您需要使其保持不變或與文件內容一起傳輸。

+0

確實是這個問題。我通過發送包含文件名和擴展名的單獨消息來解決該問題。 – PeterTheLobster