1
package bytecodeResearch;
2
3
import java.io.BufferedInputStream;
4
import java.io.BufferedWriter;
5
import java.io.FileInputStream;
6
import java.io.FileWriter;
7
import java.io.IOException;
8
9
public class ReadAndWriteClass {
10
11
//16進制數字字符集
12
private static String hexString = "0123456789ABCDEF";
13
14
/**
15
* 將字節數組的指定長度部分編碼成16進制數字字符串
16
* @param buffer 待編碼的字節數組
17
* @param length 指定的長度
18
* @return 編碼后連接而成的字符串
19
*/
20
public static String encode(byte[] buffer,int length)
21
{
22
StringBuilder sbr = new StringBuilder();
23
//將字節數組中每個字節拆解成2位16進制整數
24
for(int i=0;i<length;i++)
25
{
26
sbr.append(hexString.charAt((buffer[i]&0xf0)>>4));
27
sbr.append(hexString.charAt(buffer[i]&0x0f));
28
sbr.append(" ");
29
}
30
return sbr.toString();
31
}
32
33
/**
34
* 讀取一個Class文件,將其所有字節轉換為16進制整數,并以字符形式輸出
35
* @param inputPath 輸入文件的完整路徑
36
* @param outputPath 輸出文件的完整路徑
37
* @throws IOException 讀寫過程中可能拋出的異常
38
*/
39
public static void rwclass(String inputPath, String outputPath) throws IOException
40
{
41
//讀取Class文件要用字節輸入流
42
BufferedInputStream bis = new BufferedInputStream(
43
new FileInputStream(inputPath));
44
//輸出轉換后的文件要用字符輸出流
45
BufferedWriter bw = new BufferedWriter(
46
new FileWriter(outputPath));
47
48
int readSize = 16;
49
byte[] buffer_read = new byte[readSize];
50
String line;
51
String lineNumber = "0000000";
52
String strReplace;
53
int i = 0;
54
while ((readSize = bis.read(buffer_read,0,readSize))!= -1)
55
{
56
line = encode(buffer_read,readSize);
57
strReplace = Integer.toHexString(i);
58
lineNumber = lineNumber.substring(0, 7-strReplace.length());
59
lineNumber = lineNumber+strReplace;
60
line = lineNumber+"0h: "+line;
61
bw.write(line);
62
bw.newLine();
63
i++;
64
}
65
bis.close();
66
bw.close();
67
}
68
69
/**
70
* 程序的入口方法
71
* @param args
72
* @throws IOException
73
*/
74
public static void main(String[] args)
75
{
76
//指定輸入、輸出文件的完整路徑
77
String inputPath = "L:/HelloWorld/HelloWorld.class";
78
String outputPath = "L:/HelloWorld/HelloWorld_ByteCode.txt";
79
80
try {
81
rwclass(inputPath, outputPath);
82
System.out.println("Successfully !");
83
} catch (IOException ioe) {
84
System.err.println("Something wrong with reading or writing
!");
85
ioe.printStackTrace();
86
}
87
88
}
89
90
}
91

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84


85

86

87

88

89

90

91
