2016-06-20 7 views
0

私はサイズが2.4MBのテキストファイルを持っています大きな16進数のファイルをバイナリファイルに変換するにはどうすればよいですか?

どのように私はそれを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)); 
    } 

} 

あなたがバイナリを使用するには、Hexを変換したい場合は、この:

String hexToBinary(String hex) { 
int intVal = Integer.parseInt(hex, 16); 
String binaryVal = Integer.toBinaryString(intVal); 
return binaryVal; 
} 

あなたはそれを書いて、その後バイナリにHEX変換の組み合わせを作るために、上記の例を使用することができます。

+0

ありがとう....私は16進数のファイルを持っており、バイナリに変換するときにファイルのサイズが2.4MBであることを意味します。IDEは動作しませんし、結果を表示せず、空のファイルを生成します。 –

関連する問題