Android - 从互联网下载KML文件会导致文本乱码

时间:2018-04-10 01:57:20

标签: java android android-studio

我正在尝试从国家季节服务(第三个链接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问题。

1 个答案:

答案 0 :(得分:1)

我猜你错误地抓住了KMZ文件(参考NWS页面上的第二个链接)。 KMZ文件是PKzip压缩的,并且文件签名为“PK”作为前2个字符的字节。第二个链接中的文件将此作为第一个字节:

00000000h: 50 4B 03 04 14 00 02 00 08 00 45 81 8A 4C F5 BA ; PK........EŠLõº
00000010h: 5E 9E CD 06 02 00 13 95 07 00 07 00 1C 00 77 77 ; ^žÍ....•......ww

如果您尝试以字符串形式阅读,则会导致发布内容。