在鸿蒙Next系统中,可以通过以下步骤下载PDF文件到系统文件管理:
方法一:使用系统DownloadManager(推荐)
// 添加网络权限到config.json
"reqPermissions": [
  {
    "name": "ohos.permission.INTERNET"
  }
]
// Java代码示例
import ohos.app.Context;
import ohos.global.resource.RawFileEntry;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;
public void downloadPdf(Context context, String pdfUrl, String fileName) {
    // 创建下载请求
    DownloadConfig config = new DownloadConfig.Builder()
        .setUrl(pdfUrl)
        .setPath(AVStorage.Downloads.getPath() + "/" + fileName) // 下载到系统下载目录
        .setTitle(fileName)
        .build();
    
    // 获取DownloadManager实例
    DownloadManager downloadManager = DownloadManager.from(context);
    
    // 开始下载
    long downloadId = downloadManager.enqueue(config);
    
    // 监听下载状态(可选)
    DownloadListener listener = new DownloadListener() {
        @Override
        public void onCompleted(long id) {
            // 下载完成回调
        }
        
        @Override
        public void onFailed(long id, int errorCode) {
            // 下载失败处理
        }
    };
    downloadManager.addListener(downloadId, listener);
}
方法二:使用网络请求+文件流
// 添加权限
"reqPermissions": [
  {
    "name": "ohos.permission.INTERNET"
  },
  {
    "name": "ohos.permission.WRITE_USER_STORAGE"
  }
]
// Java代码实现
import ohos.app.Context;
import ohos.utils.zson.ZSONObject;
import java.io.InputStream;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public void downloadPdfManual(Context context, String pdfUrl, String fileName) {
    new Thread(() -> {
        try {
            URL url = new URL(pdfUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            
            // 获取下载目录路径
            String downloadPath = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getPath();
            File file = new File(downloadPath, fileName);
            
            try (InputStream inputStream = connection.getInputStream();
                 FileOutputStream outputStream = new FileOutputStream(file)) {
                
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                
                // 下载完成,可发送通知
                showDownloadCompleteNotification(context, file.getAbsolutePath());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }).start();
}
注意事项:
- 需要在config.json中声明网络和存储权限
 
- 下载路径建议使用系统预定义的下载目录
 
- 大文件下载建议使用DownloadManager以获得更好的系统兼容性
 
- 记得在UI线程外执行网络操作
 
下载完成后,文件会保存在系统的Download目录中,用户可以在文件管理应用中查看。