1+ package com .baeldung .createjar ;
2+
3+ import java .io .*;
4+ import java .util .jar .*;
5+
6+ public class JarTool {
7+ private Manifest manifest = new Manifest ();
8+
9+ public void addToManifest (String key , String value ) {
10+ manifest .getMainAttributes ()
11+ .put (new Attributes .Name (key ), value );
12+ }
13+
14+ public void addDirectoryEntry (JarOutputStream target , String parentPath , File dir ) throws IOException {
15+ String remaining = "" ;
16+ if (parentPath .endsWith (File .separator ))
17+ remaining = dir .getAbsolutePath ()
18+ .substring (parentPath .length ());
19+ else
20+ remaining = dir .getAbsolutePath ()
21+ .substring (parentPath .length () + 1 );
22+ String name = remaining .replace ("\\ " , "/" );
23+ if (!name .endsWith ("/" ))
24+ name += "/" ;
25+ JarEntry entry = new JarEntry (name );
26+ entry .setTime (dir .lastModified ());
27+ target .putNextEntry (entry );
28+ target .closeEntry ();
29+ }
30+
31+ public void addFile (JarOutputStream target , String rootPath , String source ) throws IOException {
32+ BufferedInputStream in = null ;
33+ String remaining = "" ;
34+ if (rootPath .endsWith (File .separator ))
35+ remaining = source .substring (rootPath .length ());
36+ else
37+ remaining = source .substring (rootPath .length () + 1 );
38+ String name = remaining .replace ("\\ " , "/" );
39+ JarEntry entry = new JarEntry (name );
40+ entry .setTime (new File (source ).lastModified ());
41+ target .putNextEntry (entry );
42+ in = new BufferedInputStream (new FileInputStream (source ));
43+ byte [] buffer = new byte [1024 ];
44+ while (true ) {
45+ int count = in .read (buffer );
46+ if (count == -1 )
47+ break ;
48+ target .write (buffer , 0 , count );
49+ }
50+ target .closeEntry ();
51+ in .close ();
52+ }
53+
54+ public JarOutputStream openJar (String jarFile ) throws IOException {
55+ JarOutputStream target = new JarOutputStream (new FileOutputStream (jarFile ), manifest );
56+ return target ;
57+ }
58+
59+ public void setMainClass (String mainFQCN ) {
60+ if (mainFQCN != null && !mainFQCN .equals ("" ))
61+ manifest .getMainAttributes ()
62+ .put (Attributes .Name .MAIN_CLASS , mainFQCN );
63+ }
64+
65+ public void startManifest () {
66+ manifest .getMainAttributes ()
67+ .put (Attributes .Name .MANIFEST_VERSION , "1.0" );
68+ }
69+ }
0 commit comments