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

问题描述 投票:0回答:2

我正在尝试使用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();
    }
android file sockets p2p file-sharing
2个回答
3
投票

您可以通过执行以下操作轻松找到文件扩展名:

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

0
投票

您可以从以下网址获取扩展名:

myStringURl.getUrl().substring(myStringURL.getUrl().lastIndexOf('.') + 1)
© www.soinside.com 2019 - 2024. All rights reserved.