[英]Java: File to Hex?
我有一個Java文件
FileInputStream in = null;
try{
in = new FileInputStream("C:\\pic.bmp");
}catch{}
我想將pic.bmp轉換為十六進制值數組,以便我可以編輯並將其保存為修改版本。
是否有一個java類來做這個?
你很幸運。 幾個月前我不得不這樣做。 這是一個笨拙的版本,它從命令行獲取兩個參數。 兩個命令行參數都是文件名...第一個是輸入文件,第二個是輸出文件。 輸入文件以二進制形式讀取,輸出文件以ASCII十六進制形式寫入。 希望您可以根據您的需求進行調整。
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
public class BinToHex
{
private final static String[] hexSymbols = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
public final static int BITS_PER_HEX_DIGIT = 4;
public static String toHexFromByte(final byte b)
{
byte leftSymbol = (byte)((b >>> BITS_PER_HEX_DIGIT) & 0x0f);
byte rightSymbol = (byte)(b & 0x0f);
return (hexSymbols[leftSymbol] + hexSymbols[rightSymbol]);
}
public static String toHexFromBytes(final byte[] bytes)
{
if(bytes == null || bytes.length == 0)
{
return ("");
}
// there are 2 hex digits per byte
StringBuilder hexBuffer = new StringBuilder(bytes.length * 2);
// for each byte, convert it to hex and append it to the buffer
for(int i = 0; i < bytes.length; i++)
{
hexBuffer.append(toHexFromByte(bytes[i]));
}
return (hexBuffer.toString());
}
public static void main(final String[] args) throws IOException
{
try
{
FileInputStream fis = new FileInputStream(new File(args[0]));
BufferedWriter fos = new BufferedWriter(new FileWriter(new File(args[1])));
byte[] bytes = new byte[800];
int value = 0;
do
{
value = fis.read(bytes);
fos.write(toHexFromBytes(bytes));
}while(value != -1);
fos.flush();
fos.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Java具有廣泛的圖像讀/寫和編輯庫。 查看javax.imageio
包(這是文檔 )。 您可能希望使用ImageIO
創建BufferedImage
,然后從BufferedImage
對象訪問圖像數據(有方法)。
如果你想要一個通用的答案,對於任何類型的二進制數據(不僅僅是圖像),那么我想你必須將文件的內容讀入一個字節數組。 像這樣的東西:
byte[] bytes = new byte[in.available()];
in.read(bytes);
如果在Google搜索中鍵入“java hexidecimal encoding”,第一個結果是http://commons.apache.org/codec/api-release/org/apache/commons/codec/binary/Hex.html這就是你我應該用你的問題回答“我想將pic.bmp轉換成十六進制數組的數組”。
我不知道它如何幫助你“所以我可以編輯並將其保存為修改版本”。 您可能應該使用十六進制編輯器。 例如。 ghex2
如果你想自己調整字節,從FileInputStream獲取一個FileChannel,然后分配一個ByteBuffer,然后將所有內容讀入其中。 ByteBuffer還有兩種不同的字節順序處理更大塊字節的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.