Android:如何确定文件的文件扩展名

问题描述:

我正在尝试使用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(); 
    } 

你可以这样做很容易地找到文件扩展名:

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

你可以在这个扩展来自URL的方式:

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