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

问题描述 投票:1回答:1

我正在尝试从国家气象局(第三个链接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问题。

java android android-studio
1个回答
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

如果您尝试读取字符串将导致发布的内容。

© www.soinside.com 2019 - 2024. All rights reserved.