获取的任何文件的二进制值 [英] Get binary value of any file
问题描述
如果假设我有一个文件,如的music.mp3
或 image.jpg的
或任何文件时要考虑。我如何获得这些文件的二进制重新presentation Java中的字符串值,这样我可以查看它?
If suppose I have a file such as music.mp3
or image.jpg
or any file to be considered. How do i get the binary representation of those files to a string value in java so that i can view it ??
例如:假设我有文件名为'video.mp4
则必须重新presented为 101011010101000111010
或内存类似的东西,我需要获得的价值,并将其存储在字符串如一个String =101011010101000111010
Eg: Suppose I have file called 'video.mp4'
then it must be represented as 101011010101000111010
or something like that in memory i need to get the value and store it in String like String s = "101011010101000111010"
有没有人对如何做到这一点在Java中?任何想法
Does anyone have any idea on how to do this in java ??
编辑2
我怎样才能将字符串转换回实际文件??
EDIT 2 How can i convert back the string to the actual file ??
推荐答案
我建议十六进制,它更加紧凑和可读性
I would suggest hexadecimal, it's much more compact and readable
StringBuilder sb = new StringBuilder();
try (BufferedInputStream is = new BufferedInputStream(new FileInputStream("1.txt"))) {
for (int b; (b = is.read()) != -1;) {
String s = Integer.toHexString(b).toUpperCase();
if (s.length() == 1) {
sb.append('0');
}
sb.append(s).append(' ');
}
}
System.out.println(sb);
输出
71 77 65 77 65 72 0D 0A 71 77 72 65 0D 0A 72 77 65 72 0D 0A
有关二进制字符串改变code
for binary string change the code
String s = "0000000" + Integer.toBinaryString(b);
s = s.substring(s.length() - 8);
sb.append(s).append(' ');
和得到这个输出
01110001 01110111 01100101 01110111 01100101 01110010 00001101 00001010
这是如何解析字符串和写回文件
and this is how to parse the string and write back to a file
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("2.txt"));
Scanner sc = new Scanner(s);
while (sc.hasNextInt()) {
int b = sc.nextInt(2);
out.write(b);
}
out.close();
这篇关于获取的任何文件的二进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!