2016-07-31 52 views
0

服務器(接收文件)在java中發送MP3和JPEG文件在插槽中正確超過插座

 String ip=JOptionPane.showInputDialog(this,"Enter Port Number :"); 
     String folder=jTextField2.getText(); 
     try 
     { 
     ServerSocket sskt= new ServerSocket(Integer.parseInt(ip)); 
Socket skt= sskt.accept(); 
InputStream is= skt.getInputStream(); 



byte[] bytes= new byte[1024*16]; 

DataInputStream dis=new DataInputStream(skt.getInputStream()); 
     String ext=dis.readUTF(); 

    System.out.println("extension read"); 



String path=folder+"/file."+ext; 
JOptionPane.showMessageDialog(this, path); 
File f= new File(path); 
OutputStream output = new FileOutputStream(f); 
while(is.read(bytes)>0) 
{ 
    output.write(bytes); 
System.out.println("byte read"); 
} 
System.out.println("Done!!!"); 

} 
catch(Exception e) 
{ 
System.out.println(e); 
    } 

客戶端(發送文件)

 String ip=JOptionPane.showInputDialog(this,"enter server ip:"); 
     String port=JOptionPane.showInputDialog(this,"enter port number :"); 
     File file=new File(jTextField1.getText()); 
     String name=file.getName(); 
     String n= name.substring(name.lastIndexOf(".") + 1); 



     try { 
      Socket skt=new Socket(ip, Integer.parseInt(port)); 
      OutputStream os= skt.getOutputStream(); 
      DataOutputStream dos= new DataOutputStream(os); 
      dos.writeUTF(n); 
      os.flush(); 


      FileInputStream fis= new FileInputStream(file); 
      BufferedInputStream bis= new BufferedInputStream(fis); 
      byte[] mybytearray = new byte[(int) file.length()]; 
      bis.read(mybytearray, 0, mybytearray.length); 
      os.write(mybytearray, 0, mybytearray.length); 
      JOptionPane.showMessageDialog(this,"Done!!"); 
      os.close(); 
     } 

     catch (Exception ex) { 
      System.out.println(ex); 
     } 

我能夠傳輸文件BT MP3的所有格式和jpeg文件無法正常打開。媒體播放器不能播放任何MP3文件BT在服務器上創建文件的大小是一樣的發送由客戶端

任何人都可以請幫我這個

回答

0

常見問題:無視read()返回的長度。您的副本回路都應該是這樣的:

while ((count = is.read(bytes)) > 0) 
{ 
    output.write(bytes, 0, count); 
} 

你不需要在約分配正確大小的緩衝區客戶端的所有垃圾。

+0

謝謝先生!我感謝你的努力 –