2013-02-17 89 views
0

我正在嘗試使用Socket編程在兩個Android手機之間共享文件。現在的問題是我必須在接收端硬編碼文件擴展名。有沒有一種方法可以自動確定正在接收的文件的擴展名? 這是我的代碼。Android:如何確定文件的文件擴展名

客戶端

 socket = new Socket(IP,4445); 
     File myFile = new File ("/mnt/sdcard/Pictures/A.jpg"); 
     FileInputStream fis = null; 
      fis = new FileInputStream(myFile); 
     OutputStream os = null; 
      os = socket.getOutputStream(); 
     int filesize = (int) myFile.length(); 

     byte [] buffer = new byte [filesize]; 
      int bytesRead =0; 
       while ((bytesRead = fis.read(buffer)) > 0) { 
       os.write(buffer, 0, bytesRead); 
       System.out.println("SO sendFile" + bytesRead); 
       } 
       os.flush(); 
       os.close(); 
       fis.close(); 
       socket.close(); 
     } 

和服務器端

 FileOutputStream fos = null; 
    File root = Environment.getExternalStorageDirectory(); 
      fos = new FileOutputStream(new File(root,"B.jpg")); //Here I have to hardcode B.jpg with jpg extension. 
     BufferedOutputStream bos = new BufferedOutputStream(fos); 
      ServerS = new ServerSocket(4445); 
      clientSocket = ServerS.accept(); 
     InputStream is = null; 
      is = clientSocket.getInputStream(); 

     int bytesRead = 0; 
     int current = 0; 
     byte [] mybytearray = new byte [329]; 
      do { 

       bos.write(mybytearray,0,bytesRead); 
       bytesRead = is.read(mybytearray, 0, mybytearray.length); 

       } while(bytesRead > -1); 

       bos.flush(); 
       bos.close(); 
      clientSocket.close(); 
    } 

回答

2

你可以這樣做很容易地找到文件擴展名:

String extension = filename.substring(filename.lastIndexOf('.')); 
0

你可以在這個擴展來自URL的方式:

myStringURl.getUrl()。substring(myStringURL.getUrl()。lastIndexOf('。')+ 1)