gpt4 book ai didi

Android 10 (api-29) 文件写入

转载 作者:行者123 更新时间:2023-12-03 13:27:32 27 4
gpt4 key购买 nike

任何人都可以提供关于如何在公开的 Android Q 上保存文件的准确教程,因为 getExternalFilesDir()无法在 Android Q+ 中使用。

我已经处理这个问题几天了,但无法找到任何解决方案。

我正在尝试下载一些 css、js 和 HTML 文件以将它们加载到 Webview 上。

现在,我有以下用 Kotlin 编写的代码:

companion object {
private const val TAG = "MainActivity"
private var rootDir: Path? = null
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

...

rootDir = getExternalFilesDir(null)
Log.v(TAG, "RootDir: ${rootDir!!.path}")

val cacheDir = File(rootDir!!, "cache")
if(!cacheDir.exists()) {
Log.v(TAG, "Creating cache dir (${cacheDir.path})")
try {
if (cacheDir.mkdirs())
Log.v(TAG, "Created cache dir correctly")
else
Log.v(TAG, "Could not create cache dir")
}catch (ex: IOException){
Log.e(TAG, "Could not create cache dir: ", ex)
}catch (ex: SecurityException) {
Log.e(TAG, "Not allowed to create cache dir: ", ex)
}
}

val cssDir = File(cacheDir, "css")
if(!cssDir.exists()){
Log.v(TAG, "Creating css dir (${cssDir.path})")
try {
if (cacheDir.mkdirs())
Log.v(TAG, "Created css dir correctly")
else
Log.v(TAG, "Could not create css dir")
}catch (ex: IOException){
Log.e(TAG, "Could not create css dir: ", ex)
}catch (ex: SecurityException) {
Log.e(TAG, "Not allowed to create css dir: ", ex)
}
}

val siteGlobal = File(cssDir, "site_global.css")
if(!siteGlobal.exists())
DownloadFileAsyncTask().execute(DownloadFileAsyncTask.DownloadArgs("...", siteGlobal.path))
}

和下载文件异步任务:
    private class DownloadFileAsyncTask :
AsyncTask<DownloadFileAsyncTask.DownloadArgs, Int, Void?>() {

data class DownloadArgs(val url : String, val savePath : String)

override fun doInBackground(vararg downloadFiles: DownloadArgs?): Void? {
for(downloadFile in downloadFiles) {
val urlStr = downloadFile!!.url
val outputFilePath = downloadFile.savePath
val outputFile = File(outputFilePath)
val url = URL(urlStr)

Log.v(TAG, "Connecting...")
val connection = url.openConnection() as HttpURLConnection
connection.connect()

if (connection.responseCode != HttpURLConnection.HTTP_OK) {
throw InterruptedException("Server returned HTTP ${connection.responseCode} ${connection.responseMessage}")
}

Log.v(TAG, "Connection correct")
if (!outputFile.exists()) {
Log.v(TAG, "Creating ${outputFile.path}")
outputFile.createNewFile()
}

val fileLength = connection.contentLength

val input = connection.inputStream
val output = FileOutputStream(outputFile)

val data = ByteArray(4096)
var total: Long = 0
var count: Int
Log.v(TAG, "Starting download...")
while (true) {
count = input.read(data)
if (count < 0) break
total += count
if (fileLength > 0)
publishProgress((total * 10 / fileLength).toInt())
output.write(data, 0, count)
}

output.close()
input?.close()
connection.disconnect()
}

return null
}
}

我对 Logcat 的回应是:
V/MainActivity: RootDir: /storage/emulated/0/Android/data/.../files
V/MainActivity: Creating cache dir (/storage/emulated/0/Android/data/.../files/cache)
V/MainActivity: Created cache dir correctly
V/MainActivity: Creating css dir (/storage/emulated/0/Android/data/.../files/cache/css)
V/MainActivity: Could not create css dir
V/MainActivity: Connecting...
V/MainActivity: Connection correct
V/MainActivity: Creating /storage/emulated/0/Android/data/.../files/cache/css/site_global.css

很明显,它会因 java.io.IOException: No such file or directory 而崩溃在 outputFile.createNewFile()在 AsyncTask 中,因为该目录不存在。

由于没有显示文件夹创建错误,它只告诉无法创建目录,我不知道我做错了什么。

我已添加并授予 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />万一这是问题所在,它并没有解决任何问题。

最佳答案

getExternalStorageDirectory()在 API-29 中被弃用
检查步骤

  • 从网络服务器下载和上传文件“使用 FTP 连接。(这是一种方式,但不是唯一方式)

  • How to download a file from FTP server to Android device?
  • 保存到外部存储

  •     //private static void createFile(Context ctx, String fileName, byte text)
    private static void createFile(Context ctx, String fileName, String text) {
    File filesDir = ctx.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
    assert filesDir != null;
    if (!filesDir.exists()){
    if(filesDir.mkdirs()){
    }
    }
    File file = new File(filesDir, fileName);
    try {
    if (!file.exists()) {
    if (!file.createNewFile()) {
    throw new IOException("Cant able to create file");
    }
    }
    OutputStream os = new FileOutputStream(file);
    byte[] data = text.getBytes();
    os.write(data);
    os.close();
    Log.e("TAG", "File Path= " + file.toString());
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
  • 使用加载 URL 在 webview 中加载文件并像这个问题一样注入(inject) Android Web-View : Inject local Javascript file to Remote WebpageAndroid - How to inject custom css into external webpage in webview
  • 关于Android 10 (api-29) 文件写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58049883/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com