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

时间:2013-02-17 00:12:27

标签: android file sockets p2p file-sharing

我正在尝试使用Socket编程在两部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 个答案:

答案 0 :(得分:2)

您可以通过以下方式轻松找到文件扩展名:

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

答案 1 :(得分:0)

您可以通过以下方式获取此扩展程序:

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