通过android中的socket发送大文件和文件大小

时间:2014-02-10 13:52:52

标签: android sockets filereader

之前我只通过套接字传输视频文件,但是当我需要文件大小的另一端然后出现问题,所以我想通过Socket发送Object但是文件大小限制出现了问题。它传输的文件大小为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;
}

}

1 个答案:

答案 0 :(得分:0)

我认为代码中的fileContent = new byte[(int) f.length()];可能会导致Out of memory。正如您已声明byte[] buf;,为什么不使用buf?