Java 无法正确转换二进制文件

Java 无法正确转换二进制文件,java,Java,我必须阅读一个名为test.p2b的文件,其中包含以下内容: 我试着这样读: static void branjeIzDatoteke(String location){ byte[] allBytes = new byte[10000]; try { InputStream input = new FileInputStream(location); int byteRead; int j=0; while ((

我必须阅读一个名为test.p2b的文件,其中包含以下内容:

我试着这样读:

static void branjeIzDatoteke(String location){
    byte[] allBytes = new byte[10000];
    try {
        InputStream input = new FileInputStream(location);
        int byteRead;
        int j=0;
        while ((byteRead = input.read())!=-1){
            allBytes[j] = (byte)input.read();
        }
        String str = new String(allBytes,"UTF-8");

        for (int i=0;i<=str.length()-8;i+=8){
            //int charCode = Integer.parseInt(str.substring(i,i+8),2);
            //System.out.println((char)charCode);

            int drek = (int)str.charAt(i);
            System.out.println(Integer.toBinaryString(drek));
        }
    } catch (IOException ex) {
        Logger.getLogger(Slika.class.getName()).log(Level.SEVERE, null, ex);
    }

}
static void branjeIzDatoteke(字符串位置){
字节[]所有字节=新字节[10000];
试一试{
InputStream输入=新文件InputStream(位置);
内特比德;
int j=0;
而((byteRead=input.read())!=-1){
allBytes[j]=(byte)input.read();
}
String str=新字符串(所有字节,“UTF-8”);

对于(int i=0;i如果要读取所有字节,可以使用实用程序类:

Path path = Paths.get("test.p2b");
byte[] allBytes = Files.readAllBytes(path);
String str = new String(allBytes, "UTF-8");
System.out.print(str);

您对
str
内容的迭代可能不起作用。某些UTF字符表示为代理项对,这是一个可以跨越多个
char
的代码点(如上所述)。因为您使用的是UTF,所以应该使用方法来迭代代码点,而不是字符。

您有多个缺陷。首先,在调用
input.read()时
两次。第二次只需将
byteRead
分配给数组。第二次,您不需要在while中增加变量
j
,方法是将
allBytes[j]
替换为
allBytes[j++]
你能提供这个文件吗?
String
不是二进制数据的容器。不要在这里发布文本图片。发布文本。很抱歉删除我的评论。我刚刚注意到你提到我应该使用String.codePoint()(或者更确切地说是codePoints)方法对数据进行迭代。我尝试使用如下方法:IntStream text=String.codePoints();但我收到一个错误,提示“无法从静态上下文引用非静态方法”因为我正在编写某个类的静态方法。我是否一定要更改此方法,或者是否还有任何方法可以实现此方法?在字符串实例上调用此方法,例如
str.codePoints().forEach(System.out::println)
。它不是
string
类的静态方法。