gpt4 book ai didi

java - 而不是 JSON 数据链接返回 .txt 文件如何在 android 中获取 JSON 数据

转载 作者:行者123 更新时间:2023-12-02 09:39:08 25 4
gpt4 key购买 nike

我正在使用一个链接,当我在浏览器中打开该链接时,它会生成一个 json.txt 文件并下载它。我想在 Android 应用程序中获取这个 txt 文件,并希望从这个 txt 文件中获取 JSON 数据。

最佳答案

new DownloadFileFromURL().execute("your_file_downloadable_url");

class DownloadFileFromURL extends AsyncTask<String, String, String> {

/**
* Before starting background thread
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
System.out.println("Starting download");


}

/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
int count;
try {
String root = Environment.getExternalStorageDirectory().toString();

System.out.println("Downloading");
URL url = new URL(f_url[0]);

URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();

// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);

// Output stream to write file

OutputStream output = new FileOutputStream(root+"/downloadedfile.txt");
byte data[] = new byte[1024];

long total = 0;
while ((count = input.read(data)) != -1) {
total += count;

// writing data to file
output.write(data, 0, count);

}

// flushing output
output.flush();

// closing streams
output.close();
input.close();

} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}

return null;
}



/**
* After completing background task
* **/
@Override
protected void onPostExecute(String file_url) {
System.out.println("Downloaded");

pDialog.dismiss();
}

}

关于java - 而不是 JSON 数据链接返回 .txt 文件如何在 android 中获取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57241044/

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