读取文件

public class ReadTxt {

    //读取文件
    public static void main(String[] args) {
        try {
            String str = "";
            // 1.建立连接
            FileInputStream fis = new FileInputStream("E:\\protocol\\01.txt");
            // 2.设置保存数据的字节数组
            byte[] dest = new byte[fis.available()];
            // 3.循环读取
            while (fis.read(dest) != -1) {
                // 将字节数组中的内容转换为String内容字符串输出
                str = new String(dest, 0, dest.length);
            }
            System.out.println("str : "+str);
            
            byte[] res = hex2Bytes(str);
            //复制前三个字节到totalArr数组中
            byte[] totalArr = new byte[3];
            System.arraycopy(res, 0, totalArr, 0, 3);
            int totalLen = byteToInt2(totalArr);
            System.out.println("totalLen : "+totalLen);
            
             //4.关闭流
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }

    //两位16进制表示一个字节
    public static byte[]  hex2Bytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] bytes = new byte[length];
        String hexDigits = "0123456789abcdef";
        for (int i = 0; i < length; i++) {
            int pos = i * 2; // 两个字符对应一个byte
            int h = hexDigits.indexOf(hexChars[pos]) << 4; // 注1
            int l = hexDigits.indexOf(hexChars[pos + 1]); // 注2
            if (h == -1 || l == -1) { // 非16进制字符
                return null;
            }
            bytes[i] = (byte) (h | l);
        }
        return bytes;
    }

    public static int byteToInt2(byte[] b) {
        int mask = 0xff;
        int temp = 0;
        int n = 0;
        for (int i = 0; i < b.length; i++) {
            n <<= 8;
            temp = b[i] & mask;
            n |= temp;
        }
        return n;
    }

}

 

posted @ 2019-04-30 11:46  踏月而来  阅读(166)  评论(0编辑  收藏  举报