Android - 文件在保存时会损坏

时间:2017-02-14 18:02:28

标签: java android

我从服务器下载后将文件保存到磁盘,但我相信它在保存到光盘时会损坏。如果使用chrome on mac或使用任何其他方法下载相同的文件,则文件会正常下载和读取。腐败似乎是在文件的保存过程中。我正在添加代码以帮助找出问题。该文件是一个css文件。

腐败: 读取文件时会出现一些空白字符。我尝试并注意到的一个令人惊讶的事情是,如果我将BUFFER_SIZE从4096减少到32,那么文件不会被破坏,我无法弄清楚原因。此外,减少BUFFER_SIZE会减少空格/损坏的字符。

欣赏正确方向的任何指针。感谢

private static final int BUFFER_SIZE = 4096;

// saves file to disk and returns the contents of the file.
public static String downloadFile(Context context, String filePath, String destParent) {
    String content = null;
    StringBuilder sb = new StringBuilder();
    HttpURLConnection connection = null;
    InputStream is = null;
    FileOutputStream os = null;
    String sUrl = Urls.makeWebAssetUrl(filePath); /// consider this my file URL
    String destFile = getContextBaseDir(context) + (destParent != null ? File.separator + destParent : "") + File.separator + filePath;

    try {
        URL url = new URL(sUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            File outFile = new File(destFile);
            if (!outFile.getParentFile().exists()) {
                if (!outFile.getParentFile().mkdirs()) {
                    throw new RuntimeException("Unable to create parent directories for " + filePath);
                }
            }

            is = connection.getInputStream();
            os = new FileOutputStream(outFile);

            int bytesRead = 0;
            byte[] buffer = new byte[BUFFER_SIZE];
            while ((bytesRead = is.read(buffer)) != -1) {
                sb.append(new String(buffer, 0, bytesRead, DEFAULT_ENCODING));
                os.write(buffer);
            }
            content = sb.toString();
        }
        else {
            LogUtils.LOGW(TAG, responseCode + " while connecting to " + sUrl + ": " + connection.getResponseMessage());
        }
    } catch(Exception e) {
        LogUtils.LOGE(TAG, "Error while downloading " + sUrl, e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                LogUtils.LOGE(TAG, "Error closing inputStream while downloading " + sUrl, e);
            }
        }

        if (os != null) {
            try {
                os.flush();
            } catch (IOException e) {
                LogUtils.LOGE(TAG, "Error flushing outputStream while downloading " + sUrl, e);
            }

            try {
                os.close();
            } catch (IOException e) {
                LogUtils.LOGE(TAG, "Error closing outputStream while downloading " + sUrl, e);
            }
        }
    }
    return content;
}

1 个答案:

答案 0 :(得分:0)

os.write(buffer);

问题出在这里。它应该是:

os.write(buffer, 0, bytesRead);

我不知道为什么你StringBuffer中累积内容并将其作为String返回。这不会扩大规模,在任何演员阵容中都是多余的。删除。