You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中如何下载不可读文件?项目文件更新需求咨询

解决Android应用中从URL下载文件并替代assets文件的问题

Hey there! Let's work through this problem you're having—downloading a file from that iCal URL and making sure it's readable, plus figuring out how to replace the behavior of using assets with this downloaded file. First, let's clear up a key point:

The assets folder in your APK is read-only once your app is built. You can't replace files directly in this folder after installation. Instead, you'll need to download the file to a writable location (like your app's internal storage or external storage) and then load the file from that location instead of the assets folder.

Now let's break down the solutions step by step:

1. Choose a Writable Storage Location

For most cases, using your app's internal storage is the easiest—no extra permissions needed, and the file is private to your app. Here's how to get the path:

// Get a private file directory in internal storage
File downloadDir = getFilesDir();
File targetFile = new File(downloadDir, "calendar.ics");

If you need the file to be accessible outside your app (not recommended for this use case), you can use external storage, but you'll need to handle runtime permissions for Android 6.0+.

2. Implement a Reliable Download Logic (Avoid Corrupted/Unreadable Files)

The most common reason for unreadable files is downloading them as text instead of binary, or incomplete downloads. Let's use OkHttp (a popular HTTP client) for a robust download—add this dependency to your build.gradle (Module level):

implementation 'com.squareup.okhttp3:okhttp:4.10.0'

Then here's the download code (run this on a background thread—never do network operations on the main thread!):

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
        .url("http://ade6-ujf-ro.grenet.fr/jsp/custom/modules/plannings/anonymous_cal.jsp?resources=1120&projectId=2&calType=ical&firstDate=2018-03-30&lastDate=2018-03-30")
        .build();

try (Response response = client.newCall(request).execute()) {
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

    // Write the response body (binary data) to the target file
    try (InputStream inputStream = response.body().byteStream();
         OutputStream outputStream = new FileOutputStream(targetFile)) {
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        // File is now saved correctly
    }
} catch (IOException e) {
    e.printStackTrace();
    // Handle download error (show toast, retry, etc.)
}

If you prefer using Android's native HttpURLConnection instead, here's that version:

URL url = new URL("http://ade6-ujf-ro.grenet.fr/jsp/custom/modules/plannings/anonymous_cal.jsp?resources=1120&projectId=2&calType=ical&firstDate=2018-03-30&lastDate=2018-03-30");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();

if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
    try (InputStream inputStream = connection.getInputStream();
         OutputStream outputStream = new FileOutputStream(targetFile)) {
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
    }
}
connection.disconnect();

3. Verify the Downloaded File is Readable

Once the file is saved, you can read it using a FileInputStream or any iCal parser library (like ical4j if you need to parse the calendar data):

// Example: Read the file content as a string
StringBuilder content = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(targetFile))) {
    String line;
    while ((line = reader.readLine()) != null) {
        content.append(line).append("\n");
    }
    // Use the content (e.g., parse iCal data)
} catch (IOException e) {
    e.printStackTrace();
}

4. Key Fixes for "Unreadable File" Issues

  • Always download as binary: Never use response.body().string() for binary files (like iCal)—this can corrupt the data. Use byteStream() instead.
  • Check file permissions: If using external storage, ensure you've requested WRITE_EXTERNAL_STORAGE permission (and granted it at runtime for Android 6.0+). For Android 10+, consider using MediaStore or scoped storage instead.
  • Validate the download: After downloading, check the file size matches the Content-Length header from the server to ensure the file isn't truncated.

5. Replace Assets File Usage

Wherever you were loading the file from assets, add a check: first try to load the downloaded file from your writable storage. If it doesn't exist (first run, download failed), fall back to the assets file:

InputStream inputStream;
try {
    // Try to use the downloaded file first
    inputStream = new FileInputStream(targetFile);
} catch (FileNotFoundException e) {
    // Fall back to assets if download doesn't exist
    inputStream = getAssets().open("original_calendar.ics");
}
// Use inputStream to read the file content

That should cover all the bases! Let me know if you hit any specific snags with permissions or parsing the iCal file.

内容的提问来源于stack exchange,提问作者Theoker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:21:30