我有一个大小为2.4MB的文本文件
如何将其转换为java?
我使用此代码但无效:
初始化文件:
File file = new File("E:/Binary.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
try {
String sCurrentLine;
String bits ="";
br = new BufferedReader(new FileReader("E:/base1.txt"));
while ((sCurrentLine = br.readLine()) != null) {
bits = hexToBin(sCurrentLine);
}
bw.write(bits);
bw.close();
System.out.println("done....");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
此转化方法:
static String hexToBin(String s) {
return new BigInteger(s, 16).toString(2);
}
答案 0 :(得分:0)
我不明白你的十六进制文件是什么意思,任何文件都可以作为二进制文件读取,这里有一个关于如何阅读&写一个二进制文件:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class BinaryFiles {
public static void main(String... aArgs) throws IOException{
BinaryFiles binary = new BinaryFiles();
byte[] bytes = binary.readBinaryFile(FILE_NAME);
log("size of file read in:" + bytes.length);
binary.writeBinaryFile(bytes, OUTPUT_FILE_NAME);
}
final static String FILE_NAME = "***srcPath***";
final static String OUTPUT_FILE_NAME = "***destPath***";
byte[] readBinaryFile(String aFileName) throws IOException {
Path path = Paths.get(aFileName);
return Files.readAllBytes(path);
}
void writeBinaryFile(byte[] aBytes, String aFileName) throws IOException {
Path path = Paths.get(aFileName);
Files.write(path, aBytes); //creates, overwrites
}
private static void log(Object aMsg){
System.out.println(String.valueOf(aMsg));
}
}
如果要将十六进制转换为二进制,请使用:
String hexToBinary(String hex) {
int intVal = Integer.parseInt(hex, 16);
String binaryVal = Integer.toBinaryString(intVal);
return binaryVal;
}
您可以使用上面的示例组合将HEX转换为二进制,然后编写它。