再次将字节的十进制值转换为字节

时间:2013-10-12 13:35:12

标签: java string casting integer byte

我正在使用FileInputStream从类文件中读取字节,以便从中获取所有4个字符的字符串(字符串我指的是对应于ASCII代码中的字母或数字的任何4字节序列)。我想将它们保存在大小为4的临时数组(或ArrayLists)中,然后将它们放入一个更大的ArrayList中。但是,为了使用String构造函数(String(byte [] bytes)),我仍然坚持将readed字节(FileInputStream返回int int,这是byte的十进制值)再次转换为字节。

public static void main(String[] args){
    ArrayList<String> dozapisu = new ArrayList<String>();
    ArrayList<Byte> temp = new ArrayList<Byte>();
    int c;
    File klasowe = new File("C:/Desktop/do testu/Kalendarz.class");
    try{
        FileInputStream fis = new FileInputStream(klasowe);
        while((c=fis.read()) != -1){
            if((c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122)){
                temp.add(new Byte((byte) c));
            }else{
                if(temp.size()==4){
                //  dozapisu.add(*/How should I add them?/*);
                }
            }
        }


        fis.close();
    }catch(IOException exc) {
        System.out.println(exc.toString());
        System.exit(1);
    } 
}

所以,我的问题是如何将那些重新归结的整数再次转换成字节。请原谅我的英语,如果你不理解我的问题,请要求更多翻译。

1 个答案:

答案 0 :(得分:2)

你可以这样做:

byte [] bytes = new byte[4];
int counter = 0;
while((c = fis.read()) != -1){
    if((c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122)){
        bytes[counter] = (byte)c;
        counter++;
        if(counter == 4){
            // do things with 4 byte array
            counter = 0;
        }
    }
}

如果我没有错,你需要上面的东西,对吧?

我认为使用bytes数组会比列表更好。只需跟踪数组填充的字节数。当它在数组中变为4字节时,处理完整的4字节数组,然后重置数组的计数器。

修改

要从字节创建字符串,您可以使用:

byte [] bytes = new byte[4];
int counter = 0;
while((c = fis.read()) != -1){
    if((c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122)){
        bytes[counter] = (byte)c;
        counter++;
        if(counter == 4){
            // do things with 4 byte array
            String str = new String(bytes);
            counter = 0;
        }
    }
}

字符串str将从四个字节创建。你需要的吗?