Ich speichere eine Datei auf der Festplatte nach dem Herunterladen vom Server, aber ich glaube, es wird beim Speichern auf der CD beschädigt. Wenn dieselbe Datei mit chrome on mac oder einer anderen Methode heruntergeladen wird, wird die Datei normal heruntergeladen und gelesen. Die Korruption scheint in dem Speichervorgang der Datei zu sein. Ich füge den Code hinzu, um das Problem herauszufinden. Die Datei ist eine CSS-Datei.Android - Datei korrumpiert beim Speichern
Korruption: Beim Lesen der Datei werden einige Leerzeichen angezeigt. Eine überraschende Sache, die ich versuchte und bemerkte, ist, dass, wenn ich BUFFER_SIZE von 4096 auf 32 reduziere, die Datei nicht beschädigt wird, ich konnte nicht herausfinden warum. Wenn Sie BUFFER_SIZE reduzieren, werden auch Leerzeichen/beschädigte Zeichen reduziert.
Schätzen Sie alle Zeiger in die richtige Richtung. Dank
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;
}
Vielen Dank, das war das Problem. Gelöst jetzt :) –