空字符串判断空失败

起因是在处理文件的时候,想要自己存入一个固定长度头部,这里是1024个字节,在读取之后获取到一个看似字符串的对象,但是在判空时候失败了。

原因是这个看似为空字符串的对象内部char数组中有内容 \u0000,只是显示为空字符串。

image

Demo 以下为复现代码

public static void main(String[] args) {

        String path  = "D:/wbcData";

        //将一个字符串 写入到文件
        try(OutputStream outputStream = Files.newOutputStream(Paths.get(path))) {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("1");
            stringBuilder.append(",");
            stringBuilder.append("2");
            stringBuilder.append(",");
            stringBuilder.append("3");
            stringBuilder.append(",");

            byte[] bytes1 = new byte[1024];
            byte[] bytes2 = stringBuilder.toString().getBytes();
            System.out.println(bytes2.length);

            for (int i = 0; i < bytes2.length; i++) {
                bytes1[i] = bytes2[i];
            }

            outputStream.write(bytes1,0,1024);
        }catch (Exception e){
            e.printStackTrace();
        }

        //再读取出来之后,分割得到的一个空字符 它不是空字符串
        try(InputStream inputStream = Files.newInputStream(Paths.get(path))) {
            byte[] head = new byte[1024];
            int read = inputStream.read(head);
            System.out.println(read);
            String s1 = new String(head);
            System.out.println(s1);
            String[] headList = s1.split(",");

            for (String s : headList) {
                System.out.println("本次循环的字符:【"+s+"】");
                System.out.println("本次循环的字符长度:【"+s.length()+"】");
                System.out.println(Integer.parseInt(s));
            }

        }catch (Exception e){
            e.printStackTrace();
        }

    }

自行记录一下bug

posted @ 2022-11-18 10:11  不一样的爪哇  阅读(78)  评论(0编辑  收藏  举报