【问题标题】:sending large file along with file size through socket in android通过android中的套接字发送大文件以及文件大小
【发布时间】:2014-02-10 13:52:52
【问题描述】:

之前我只通过套接字传输视频文件,但是当我需要另一端的文件大小时出现问题,所以我想通过套接字发送对象,但文件大小限制存在问题。它传输的文件大小最大为 45MB我想传输更多大小的文件。
我在下面发布了代码:

public class WiFiDirectBundle implements Serializable {
private String fileName;
private String fileType;
private Long fileSize;

ArrayList<byte[]> chunks;
ArrayList<Integer> a;
static int len=0;
byte[] buf;

public WiFiDirectBundle() {
    // TODO Auto-generated constructor stub
}

public void setFile(String path) throws FileNotFoundException,
IOException {
    File f = new File(path);

    fileName = f.getName();
    fileType = MimeTypeMap.getFileExtensionFromUrl(f.getAbsolutePath());
    fileSize = f.length();
    Log.d(WiFiDirectActivity.TAG,"name of file is"+fileName);
    Log.d(WiFiDirectActivity.TAG,"size of file is"+fileSize);

    FileInputStream fin = null;
    try {
        fin = new FileInputStream(f);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }  



   fileContent = new byte[(int) f.length()];
    try {
        fin.read(fileContent);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    fin.close();

}

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


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

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

    return null;
}

}

【问题讨论】:

    标签: android sockets filereader


    【解决方案1】:

    我认为您代码中的这个fileContent = new byte[(int) f.length()]; 可能会导致Out of memory。既然你已经声明了byte[] buf;,为什么不改用一个buf呢?

    【讨论】:

    • 你能不能用 n xampl 详细说明一下,谢谢你
    • 你可以试试这样的代码:buf = new byte[1000]; while(fis.read(buf) != -1){ fos.write(buf); }
    猜你喜欢
    • 2017-03-14
    • 2012-07-12
    • 1970-01-01
    • 2012-01-30
    • 2014-06-19
    • 2017-08-26
    • 2013-12-15
    • 2015-09-15
    • 2012-07-12
    相关资源
    最近更新 更多