Java文件以二进制的转换 [英] Java File to Binary Conversion
问题描述
如何将文件转换为二进制?我只需要它为我的项目。我需要它的二进制文件为加密文件。
How can i convert File to Binary? I just need it for my project. I need to encrypt a file by its binaries.
推荐答案
如果你指的是在访问实际的二进制形式再读取该文件中,每一个字节转换为二进制重新presentation ...
If you're referring to accessing the ACTUAL BINARY form then read in the file and convert every byte to a binary representation...
编辑:
下面是一些code到一个字节转换成同位的字符串:
Here's some code to convert a byte into a string with the bits:
String getBits(byte b)
{
String result = "";
for(int i = 0; i < 8; i++)
result += (b & (1 << i)) == 0 ? "0" : "1";
return result;
}
如果你指的是访问该字节的文件,然后简单地使用下面的code(您可以使用此为第一种情况为好):
If you're referring to accessing the bytes in the file then simply use the following code (you can use this for the first case as well):
File file = new File("filename.bin");
byte[] fileData = new byte[file.length()];
FileInputStream in = new FileInputStream(file);
in.read(fileData):
in.close();
// now fileData contains the bytes of the file
要使用这两个code片,您现在可以遍历每一个字节,并创建一个比特一个String对象(8倍于原始文件大小!!大):
To use these two pieces of code you can now loop over every byte and create a String object (8X larger than the original file size!!) with the bits:
String content = "";
for(byte b : fileData)
content += getBits(b);
// content now contains your bits.
这篇关于Java文件以二进制的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!