【问题标题】:How to get the file name of a file which is transferred via wifi direct in android?如何在android中获取通过wifi直接传输的文件的文件名?
【发布时间】:2013-05-29 04:52:44
【问题描述】:

我看过一个关于这个问题的例子。但是当我尝试它时,它只是在这段代码中发生错误File f = new File(Uri.parse(uri.toString()));,只是说构造函数文件(Uri)是未定义的。我已经陷入这个错误很多天了。我不知道有什么问题,因为其他人可以工作。以下是建议代码

public class WiFiDirectBundle extends Serializable {
    private String fileName;
    private String mimeType;
    private Long fileSize;
    private byte[] fileContent;

    public WiFiDirectBundle() {}

    // adds a file to the bundle, given its URI
    public void setFile(Uri uri) {
        File f = new File(Uri.parse(uri.toString()));

        fileName = f.getName();
        mimeType = MimeTypeMap.getFileExtensionFromUrl(f.getAbsolutePath());
        fileSize = f.length();

        FileInputStream fin = new FileInputStream(f);        
        fileContent = new byte[(int) f.length()];
        fin.read(fileContent);
    }

    // restores the file of the bundle, given its directory (change to whatever
    // fits you better)
    public String restoreFile(String baseDir) {
        File f = new File(baseDir + "/" + fileName);
        try {
            FileOutputStream fos = new FileOutputStream(f);
            if (fileContent != null) {
                fos.write(fileContent);
            }

            fos.close();
            return f.getAbsolutePath();

        } catch (IOException e) {
                e.printStackTrace();
        }

        return null;
    }

    public String getFileName() {
        return fileName;
    }

    public String getMimeType() {
        return mimeType;
    }

    public Long getFileSize() {
        return fileSize;
    }
}

这是原始问题: How to find file name of a file which is transferred via wifi direct mode in android? 另外我是Wifi Direct的初学者,我可以成功链接两个设备并传输文件,但我想链接更多设备并依次传输文件有人可以给我一些关于学习它的建议或一些关于如何做的例子。谢谢!

【问题讨论】:

标签: android file-transfer wifi-direct


【解决方案1】:

使用

File f = new File(uri.getPath());

而不是

File f = new File(Uri.parse(uri.toString()));

从 Uri 获取文件路径

【讨论】:

  • 感谢您的回答!我刚刚尝试了您的建议,但在以下两行中出现了其他错误 FileInputStream fin = new FileInputStream(f); and fin.read(fileContent); 它分别表示未处理的异常类型 FileNotFoundException 和未处理的异常类型 IOException。新出现的错误应该如何处理?
  • @dddog : jsut 使用日志调试您的代码并检查您是否从uri.getPath() 获得有效路径
【解决方案2】:

您可以使用内容解析器从其 uri 打开文件的输入流 内容解析器 cr=getContentResolver(); InputStream in=cr.OpenInputStream(file_uri); 您可以使用此输入流从文件中读取数据

【讨论】:

    猜你喜欢
    • 2017-01-17
    • 2013-04-04
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多