java - 怎么把object 转成 数组

 失望与痛心 发布于 2022-11-02 23:47
用的是 jBittorrentAPI.jar 解析种子文件。
public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        // t1();
        Object a = new Object();
        
        File f = new File("c:\\a.torrent");
        InputStream in = new FileInputStream(f);
        BufferedInputStream is = new BufferedInputStream(in);
        Map m = BDecoder.decode(is);
         System.out.println("通过Map.keySet遍历key和value:");
         for (String key : m.keySet()) {
         System.out.println("key= " + key + " and value= " + m.get(key));
         }

        Map info = (Map) m.get("info");
        Object param = info.get("name");
        //这个 param 是个 int数组,但是强转却出现强制类型转换错误。。想不明白
        
     }

接着问题又来了,种子内的文件名 理论上是 ascii 编码,但是我发现如果包含中文 就会出现负数 。。。ascii编码里没有负数,那这个是数字是什么,怎么变成中文。。

-25
-89
-69
-27
-118
-88
-24
-65
-73
-27
-82
-85
46
66
68
46
55
50
48
112
46
-27
-101
-67
-24
-117
-79
-27
-113
-116
-24
-81
-83
46
-28
-72
-83
-24
-117
-79
-27
-113
-116
-27
-83
-105
-27
-71
-107
46
109
107
118

4 个回答
  • 已实测 请看:
    public static void main(String[] args) {

    // TODO Auto-generated method stub
    byte[] b = {10,84,101,46};
    Object param  = b;
    byte[] b1 = (byte[])param;
    int length = b1.length;
    int[] c = new int[b1.length];
    for(int i = 0; i < length; i++){
        c[i] = b1[i];
        System.out.println(c[i]);
    }            

    }

    //输出:
    10
    84
    101
    46。
    补充一点:思路 byte[]不能直接转int[],但byte可以转int,for循环一个一个来即可。

    2022-11-12 01:40 回答
  • 你是怎么转的?把转换代码和报错信息贴一下看看。

    2022-11-12 01:40 回答
  • 请问哪里看出param是个int数组了?

    报错信息中提示param的类型是[B, 也就是byte[],不能转化为[Ljava.lang.Integer


    http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getName%28%29


    java中的 byte是有符号的,一个字节的范围是0~255, 转化成有符号数字,就变成了

    0, 1, 2, ... 125, 126, 127, -127, -126, ... -3, -2, -1
    

    byte[]转化成String ,用

    byte[] bytes = .... ;
    new String(bytes); // 使用默认编码
    new String(bytes, "utf-8"); // 指定编码

    另外你又哪里看出来是ascii编码了。。 汉字几千个,ascii码才127个。。。

    一个字节,ascii码只占了一半的空间,剩下的都被其他编码用了,用于扩充各国语言,具体不展开了, 百度搜索gbk、utf-8、unicode之类的先了解一下

    2022-11-12 01:40 回答
  • 試試cast成String

    2022-11-12 01:40 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有