【发布时间】:2018-09-19 12:17:20
【问题描述】:
我正在尝试从国家气象局(第三个链接here)下载一个文件,将其作为文件保存在本地存储中,然后将该文件的内容转换为可用的字符串。但是,我遇到了一个问题,即文件中的文本被乱码成完全无法使用的字符和符号,尽管我知道实际的 KML 文件本身是可以查看的。
这是我用来下载文件的代码。我会注意到我对 Android 开发还很陌生,所以这段代码基本上是不同教程的合并。
编辑:下面的行是我在运行此代码时看到的示例。
PK�������~�L�]�[��S�������
protected String doInBackground(String... inputUrl) {
int count;
String filepath;
String result = "";
Date currentTime = Calendar.getInstance().getTime();
try{
File file = new File(context.getFilesDir(), "data_" + currentTime);
URL url = new URL(inputUrl[0]);
URLConnection connection = url.openConnection();
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream());
BufferedOutputStream outputStream = new BufferedOutputStream(fileOutputStream, 8192);
byte data[] = new byte[1024];
while ((count = inputStream.read(data)) != -1){
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
filepath = file.getAbsolutePath();
result = getStringFromFile(filepath);
} catch (Exception e){
Log.e("DownloadDataAsync", "Download data failed " + e.toString());
}
return result;
}
getStringFromFile() 函数来自 Stack Overflow 上的this 问题。
【问题讨论】:
-
你在什么时候看到你说的结果是乱码 - 它是在'onPostExecute'还是异步任务的调用者。发布的代码作为独立的 java 工作。
-
执行
getStringFromFile()后,生成的字符串只包含不可用的文本和符号。这将是onPostExecute,此时我看到的结果看起来像这样,尽管在调试中我可以看到文件的每一行在读入字符串时都显示为这些字符。我将使用我所看到的示例行来更新原始问题。 -
似乎是编码问题,但文件是 UTF-8,默认流类型也是 UTF-8,所以看起来不是问题。
-
一开始我也是这么想的。在我的问题中添加了结果字符串的第一行作为我所看到的示例。
-
这很有趣 - PK(前 2 个字符)是 PKZip 文件的文件签名 - 也许只是巧合。
标签: java android android-studio