java
主页 > 软件编程 > java >

Java实现Jar文件的遍历复制与文件追加

2024-12-02 | 佚名 | 点击:

一、引入依赖

1

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

<dependency>

    <groupId>commons-io</groupId>

    <artifactId>commons-io</artifactId>

    <version>2.5</version>

</dependency>

<!-- slf4j + log4j2 begin -->

<dependency>

    <groupId>org.apache.logging.log4j</groupId>

    <artifactId>log4j-slf4j-impl</artifactId>

    <version>2.12.1</version>

</dependency>

<!-- log4j end -->

<dependency>

    <groupId>org.projectlombok</groupId>

    <artifactId>lombok</artifactId>

    <version>1.18.12</version>

    <scope>provided</scope>

</dependency>

<dependency>

    <groupId>org.apache.commons</groupId>

    <artifactId>commons-compress</artifactId>

    <version>1.23.0</version>

    <scope>test</scope>

</dependency>

<dependency>

    <groupId>junit</groupId>

    <artifactId>junit</artifactId>

    <version>4.12</version>

    <scope>test</scope>

</dependency>

二、文件准备

三、Java编码实现

1

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

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.util.jar.JarEntry;

import java.util.jar.JarInputStream;

import java.util.jar.JarOutputStream;

 

import org.apache.commons.io.IOUtils;

import org.apache.commons.lang3.SystemUtils;

import org.apache.commons.lang3.time.DateFormatUtils;

import org.junit.Test;

 

import lombok.extern.slf4j.Slf4j;

 

/**

 * @author 00fly

 *

 */

@Slf4j

public class JarEntryTest

{

    /**

     * JDK-API实现-将addFiles添加到srcJar并重命名为newJar

     *

     * @param srcJar

     * @param newJar

     * @param addFiles

     * @throws IOException

     */

    private void addFilesToJar(File srcJar, String newJar, File... addFiles)

        throws IOException

    {

        try (JarInputStream jis = new JarInputStream(new FileInputStream(srcJar)); JarOutputStream jos = new JarOutputStream(new FileOutputStream(newJar), jis.getManifest()))

        {

            JarEntry jarEntry;

            while ((jarEntry = jis.getNextJarEntry()) != null)

            {

                jos.putNextEntry(jarEntry);

                IOUtils.copy(jis, jos);

            }

             

            // 追加文件

            for (File addFile : addFiles)

            {

                jarEntry = new JarEntry("add/" + addFile.getName());

                jos.putNextEntry(jarEntry);

                try (InputStream entryInputStream = new FileInputStream(addFile))

                {

                    IOUtils.copy(entryInputStream, jos);

                }

            }

        }

    }

     

    /**

     * 拷贝 Jar

     *

     * @param fromJar

     * @param toJar

     * @throws IOException

     */

    private void copyJar(String fromJar, String toJar)

        throws IOException

    {

        try (JarInputStream jis = new JarInputStream(new BufferedInputStream(new FileInputStream(fromJar))); JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(toJar)), jis.getManifest()))

        {

            JarEntry je;

            while ((je = jis.getNextJarEntry()) != null)

            {

                jos.putNextEntry(je);

                int iRead;

                while ((iRead = jis.read()) != -1)

                {

                    jos.write(iRead);

                }

            }

            jis.closeEntry();

            jos.finish();

        }

    }

     

    @Test

    public void testAddFiles()

    {

        try

        {

            String src = getClass().getResource("/apache-jstl.jar").getPath();

            String add1 = getClass().getResource("/servlet-api.jar").getPath();

            String add2 = getClass().getResource("/log4j2.xml").getPath();

            String newJar = src.replace(".jar", DateFormatUtils.format(System.currentTimeMillis(), "_HHmmssSSS") + ".jar");

            log.info("源文件: {}", src);

            log.info("++新增: {}", add1);

            log.info("++新增: {}", add2);

            log.info("新文件: {}", newJar);

            addFilesToJar(new File(src), newJar, new File(add1), new File(add2));

        }

        catch (IOException e)

        {

            log.error(e.getMessage(), e);

        }

    }

     

    @Test

    public void testCopy()

    {

        try

        {

            String src = getClass().getResource("/servlet-api.jar").getPath();

            String newJar = src.replace(".jar", DateFormatUtils.format(System.currentTimeMillis(), "_HHmmssSSS") + ".jar");

            log.info("源文件: {}", src);

            log.info("新文件: {}", newJar);

            copyJar(src, newJar);

             

            if (SystemUtils.IS_OS_WINDOWS)

            {

                Runtime.getRuntime().exec("cmd /c start " + new File(newJar).getParentFile().getCanonicalPath());

            }

        }

        catch (IOException e)

        {

            log.error(e.getMessage(), e);

        }

    }

     

    /**

     * 遍历打印

     *

     * @throws IOException

     */

    @Test

    public void testList()

        throws IOException

    {

        String src = getClass().getResource("/servlet-api.jar").getPath();

        try (JarInputStream jis = new JarInputStream(new BufferedInputStream(new FileInputStream(src))))

        {

            JarEntry je;

            while ((je = jis.getNextJarEntry()) != null)

            {

                System.out.println(je.getName());

            }

            jis.closeEntry();

        }

    }

}

四、Compress编码实现

Compress 功能非常强大,可以参考官网样例:

https://commons.apache.org/proper/commons-compress/examples.html

1

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

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.nio.charset.StandardCharsets;

 

import org.apache.commons.compress.archivers.ArchiveOutputStream;

import org.apache.commons.compress.archivers.jar.JarArchiveEntry;

import org.apache.commons.compress.archivers.jar.JarArchiveInputStream;

import org.apache.commons.compress.archivers.jar.JarArchiveOutputStream;

import org.apache.commons.io.IOUtils;

import org.apache.commons.lang3.StringUtils;

import org.apache.commons.lang3.time.DateFormatUtils;

import org.junit.Test;

 

import lombok.extern.slf4j.Slf4j;

 

@Slf4j

public class CompressTest

{

    @Test

    public void test()

        throws IOException

    {

        String src = getClass().getResource("/apache-jstl.jar").getPath();

        String add1 = getClass().getResource("/servlet-api.jar").getPath();

        String add2 = getClass().getResource("/log4j2.xml").getPath();

        String newJar = src.replace(".jar", DateFormatUtils.format(System.currentTimeMillis(), "_HHmmssSSS") + ".jar");

        log.info("源文件: {}", src);

        log.info("++新增: {}", add1);

        log.info("++新增: {}", add2);

        log.info("新文件: {}", newJar);

         

        try (JarArchiveInputStream jarInput = new JarArchiveInputStream(new FileInputStream(src)); ArchiveOutputStream outputStream = new JarArchiveOutputStream(new FileOutputStream(newJar)))

        {

            JarArchiveEntry jarEntry;

            while ((jarEntry = jarInput.getNextJarEntry()) != null)

            {

                outputStream.putArchiveEntry(jarEntry);

                IOUtils.copy(jarInput, outputStream);

            }

            outputStream.flush();

             

            // 追加addFiles

            String[] addFiles = {add1, add2};

            for (String addFile : addFiles)

            {

                JarArchiveEntry addEntry = new JarArchiveEntry("add/" + StringUtils.substringAfterLast(addFile, "/"));

                outputStream.putArchiveEntry(addEntry);

                try (InputStream entryInputStream = new FileInputStream(addFile))

                {

                    IOUtils.copy(entryInputStream, outputStream);

                }

            }

             

            // 追加add/001.txt

            JarArchiveEntry entry = new JarArchiveEntry("add/001.txt");

            outputStream.putArchiveEntry(entry);

            outputStream.write("org.apache.commons.compress.archivers.jar.JarArchiveOutputStream;".getBytes(StandardCharsets.UTF_8));

            outputStream.closeArchiveEntry();

            outputStream.finish();

        }

    }

}

原文链接:
相关文章
最新更新