2009-11-11 101 views
2

我创建从我的Java代码的JAR文件:创建一个JAR文件编程

public void create() throws IOException{ 
    FileOutputStream stream = new FileOutputStream(this.packagePath); 
    JarOutputStream out = new JarOutputStream(stream, new Manifest()); 
    out.close(); 
    //jarFile = new JarFile(new File(this.packagePath)); 
} 

我得到一个META-INF目录,里面一个MANIFEST.MF文件。

现在,当我想将文件添加到jar文件:

public void addFile(File file) throws IOException{ 

    //first, make sure the package already exists 
    if(!file.exists()){ 
     throw new IOException("Make" + 
       " sure the package file already exists.you might need to call the Package.create() " + 
       "method first."); 
    } 

    FileOutputStream stream = new FileOutputStream(this.packagePath); 
    JarOutputStream out = new JarOutputStream(stream); 
    /*if(jarFile.getManifest()!=null){ 
     out = new JarOutputStream(stream,jarFile.getManifest()); 
    }else{ 
     out=new JarOutputStream(stream); 
    }*/ 

    byte buffer[] = new byte[BUFFER_SIZE];  
    JarEntry jarEntry = new JarEntry(file.getName()); 
    jarEntry.setTime(file.lastModified()); 
    out.putNextEntry(jarEntry); 

    //Write file to archive 
    FileInputStream in = new FileInputStream(file); 

    while (true) { 
     int nRead = in.read(buffer, 0, buffer.length); 
     if (nRead <= 0) 
     break; 
     out.write(buffer, 0, nRead); 
    } 
    in.close();  
    out.close(); 
} 
将文件添加到使用上述代码的JAR档案文件时

,其MANIFEST.MF的META-INF目录中消失,我得到新添加的文件。

我想能够将文件添加到jar,并仍然获取清单文件。在清单文件中,我想要一个带有新添加jar名称的行。

谢谢。

回答

1

我认为你不能添加一个新的条目,因为你不能打开jar包“append”。我认为你必须创建一个新的jar文件并从旧的复制条目,并添加您的条目​​。

3
  1. 包括在你的项目的classpath
  2. 代码
    Jar jar = new Jar(); 
    //configure the jar object 
    jar.execute();

here关于您可以设置的参数信息的ant.jar文件。

+0

+1代码重用 – 2009-11-11 18:12:23

0
FileOutputStream stream = new FileOutputStream(this.packagePath); 

此行将创建一个新的空文件。

要编辑一个jar文件,您需要备份旧版本并将其条目复制到新的jar文件中。