2016-06-20 121 views
0

我有一个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); 
} 
+1

什么是你的问题? –

+0

这种方式不工作,当我尝试它没有发生 –

+1

你是什么意思的“没有发生”?它创建了一个文件,还是不是?该文件是否为空?当您使用文本编辑器将文件作为文本文件打开时,是否包含“1”字符和“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转换为二进制然后写它的组合。

+0

谢谢....我的意思是我有十六进制文件和文件大小是2.4MB,当我转换为二进制它不起作用IDE不显示任何结果并生成空文件原因该文件是大 –

相关问题