如何从包含 java 中的字符串的文件中解码字节?
How to decode bytes from file that contains strings in java?
我有一个文件,其中包含一个字符串,后跟字节,这些字节包含编码在其中的二进制数字。
Thisisastring. �J
在我的代码中,我尝试忽略字符串并专注于解码由 space 分隔的字节。当我 运行 代码时,结果似乎是正确的,只是第一个二进制数偏离了很多。
StringBuffer buffer = new StringBuffer();
File file = new File(arg);
FileInputStream in = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(in, "UTF8");
Reader inn = new BufferedReader(isr);
int ch;
while ((ch = inn.read()) > -1){
buffer.append((char)ch);
}
inn.close();
String content = buffer.toString();
String temp = new String();
for(int i=0; i<content.length(); i++){
temp += content.charAt(i);
if(content.charAt(i) == ' '){
while(i != content.length()-1){
i++;
byte b = (byte) content.charAt(i);
String x = Integer.toString(b & 0xFF, 2);
System.out.println(x);
}
}
}
结果:
11111101 <- Why is only this one incorrect?
11000
1001010
1011
期望值:
10010101
00011000
01001010
1011
您不应该对二进制数据使用 Readers
或 Strings
。
StringBuffer buffer = new StringBuffer();
File file = new File(arg);
FileInputStream in = new FileInputStream(file);
DataInputStream dis = new DataInputStream(new BufferedInputStream(in));
int ch;
while ((ch = din.read()) > -1){
buffer.append((char)ch);
if (ch == ' ')
{
// next byte is a binary value
byte b = din.readByte();
String x = Integer.toString(b & 0xFF, 2);
System.out.println(x);
}
}
我有一个文件,其中包含一个字符串,后跟字节,这些字节包含编码在其中的二进制数字。
Thisisastring. �J
在我的代码中,我尝试忽略字符串并专注于解码由 space 分隔的字节。当我 运行 代码时,结果似乎是正确的,只是第一个二进制数偏离了很多。
StringBuffer buffer = new StringBuffer();
File file = new File(arg);
FileInputStream in = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(in, "UTF8");
Reader inn = new BufferedReader(isr);
int ch;
while ((ch = inn.read()) > -1){
buffer.append((char)ch);
}
inn.close();
String content = buffer.toString();
String temp = new String();
for(int i=0; i<content.length(); i++){
temp += content.charAt(i);
if(content.charAt(i) == ' '){
while(i != content.length()-1){
i++;
byte b = (byte) content.charAt(i);
String x = Integer.toString(b & 0xFF, 2);
System.out.println(x);
}
}
}
结果:
11111101 <- Why is only this one incorrect?
11000
1001010
1011
期望值:
10010101
00011000
01001010
1011
您不应该对二进制数据使用 Readers
或 Strings
。
StringBuffer buffer = new StringBuffer();
File file = new File(arg);
FileInputStream in = new FileInputStream(file);
DataInputStream dis = new DataInputStream(new BufferedInputStream(in));
int ch;
while ((ch = din.read()) > -1){
buffer.append((char)ch);
if (ch == ' ')
{
// next byte is a binary value
byte b = din.readByte();
String x = Integer.toString(b & 0xFF, 2);
System.out.println(x);
}
}