サーバーからファイルをダウンロードした後にファイルをディスクに保存していますが、ディスクに保存中にファイルが破損していると思われます。同じファイルがMacでchromeを使用してダウンロードされたり、他の方法でダウンロードされた場合、ファイルは正常にダウンロードされ、読み込まれます。破損は、ファイルの保存プロセスにあるようです。問題を見つけるのに役立つコードを追加しています。このファイルはCSSファイルです。Android - 保存中にファイルが壊れる
破損: ファイルを読むときに空白の種類の文字が表示されます。私が試して驚いたことは、4096から32にBUFFER_SIZEを減らしても、ファイルが壊れないという理由が分かりません。また、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;
}
ありがとう、これは問題でした。今解決した:) –