zoukankan      html  css  js  c++  java
  • 读取文件

    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;
        }
    
    }
  • 相关阅读:
    用Lua编写ACM算法竞赛开灯问题
    糟糕的中文版龙书
    font and face, 浅探Emacs字体选择机制及部分记录
    栈与卡特兰数
    关于2018年东南大学Robomaster算法组工作的总结
    C++中的默认参数规则
    MySQL第三章——嵌套查询
    MySQL第三章——空值的处理
    MySQL第三章——数据更新
    MySQL第三章——连接查询
  • 原文地址:https://www.cnblogs.com/moris5013/p/10795165.html
Copyright © 2011-2022 走看看