前有有講過,如何通過JAVA,將JAR製作成自解壓的exe文件。現收到需求:用戶下載exe時,自動往exe文件中添加或覆蓋某文件。
思路:

1、由於自解壓的exe文件由sfx、config.txt、7z壓縮文件組成。所以直接用SevenZFile是打不開該文件的。
2、從exe文件中,找到config.txt結尾標識的位置(pos).
3、將exe文件拆會成兩具臨時文件件:sfx+config.txt文件,z7.7z壓縮包文件。
4、調用SevenZFile,添加中覆蓋文件組成新的壓縮文件newz7.7z壓縮包。
5、合併sfx+config.txt文件、newz7.7z壓縮包成exe生解壓文件。
代碼如下:
其中:d:\test\7z自解壓.exe 為自解壓exe文件。
/**
* 查找文件中的config.txt結尾位置
*
* @throws IOException
*/
@Test
public void getConfigEndPosTest() throws IOException {
final File exeFile = new File("d:\test\7z自解壓.exe");
final byte[] configEnd= ";!@InstallEnd@!".getBytes("ISO-8859-1");
final BufferedInputStream exeBis = new BufferedInputStream(new FileInputStream(exeFile));
// sfx假定大於124928
exeBis.skip(124928);
int b;
long pos = 124928;
int macth = 0;
while ((b = exeBis.read()) != -1) {
pos++;
if (configEnd[macth] == b) {
macth++;
} else {
macth = 0;
}
if (macth == 15) {
System.out.print(pos);
break;
}
}
exeBis.close();
}
/**
* 自解壓文件拆分成: sfx+config, 7z兩個臨時文件
*
* @throws IOException
*/
@Test
public void splitFileTest() throws IOException {
final File exeFile = new File("d:\test\7z自解壓.exe");
final FileInputStream exeIn = new FileInputStream(exeFile);
final File sfxFile = new File("d:\test\sfx.tmp");
sfxFile.createNewFile();
final FileOutputStream sfxOs = new FileOutputStream(sfxFile);
// 125070 第一步求得的pos
byte[] buffer = new byte[125070];
int length;
length = exeIn.read(buffer);
sfxOs.write(buffer, 0, length);
sfxOs.close();
final File z7File = new File("d:\test\z7.7z");
z7File.createNewFile();
final FileOutputStream z7Os = new FileOutputStream(z7File);
while ((length = exeIn.read(buffer)) > 0) {
z7Os.write(buffer, 0, length);
}
z7Os.close();
exeIn.close();
}
/**
* 添加或覆蓋的文件到7z
*
* @throws IOException
*/
@Test
public void writeFileTo7z() throws IOException {
//略,7z文件處理
}
/**
* sfx+config + 新的7z文件成exe.
* @throws IOException
*/
@Test
public void mergeFile() throws IOException {
//略, 參考前一篇的《JAVA JAR製作可自運行的EXE包》
}原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/258814.html
微信掃一掃
支付寶掃一掃