Как сделать Zip / Jar в Java, который не будет содержать абсолютный путь - PullRequest
1 голос
/ 15 февраля 2012

Я создаю файл .jar на Java, но .jar содержит абсолютный путь к месту его нахождения в системе (/ tmp / tempXXX / foo вместо / foo).Дерево выглядит так:

.
|-- META-INF
|-|- ....
|-- tmp
|-|- tempXXX
|-|-|- foo
|-|-|- bar

Вместо этого:

.
|-- META-INF
|-|- ....
|-- foo
|-- bar

Возможно ли это исправить?Вот функция, которая делает это:

public static void add(File source, JarOutputStream target, String removeme)
        throws IOException
{
    BufferedInputStream in = null;
    try
    {
        File source2 = source;
        if (source.isDirectory())
        {
            String name = source2.getPath().replace("\\", "/");
            if (!name.isEmpty())
            {
                if (!name.endsWith("/"))
                    name += "/";
                JarEntry entry = new JarEntry(name);
                entry.setTime(source.lastModified());
                target.putNextEntry(entry);
                target.closeEntry();
            }
            for (File nestedFile : source.listFiles())
                add(nestedFile, target, removeme);
            return;
        }

        JarEntry entry = new JarEntry(source2.getPath().replace("\\", "/"));
        entry.setTime(source.lastModified());
        target.putNextEntry(entry);
        in = new BufferedInputStream(new FileInputStream(source));

        byte[] buffer = new byte[2048];
        while (true)
        {
            int count = in.read(buffer);
            if (count == -1)
                break;
            target.write(buffer, 0, count);
        }
        target.closeEntry();
    }
    finally
    {
        if (in != null)
            in.close();
    }
}

Переменная source2 была создана для изменения пути, но при изменении выдает ошибку «Invalid .jar file».Модификация была такой:

File source2 = new File(source.getPath().replaceAll("^" + removeme, ""));

Редактировать: теперь работает.Вот новый код, если кому-то интересно:

public static void add(File source, JarOutputStream target, String removeme)
        throws IOException
{
    BufferedInputStream in = null;
    try
    {
        File parentDir = new File(removeme);
        File source2 = new File(source.getCanonicalPath().substring(
                parentDir.getCanonicalPath().length() + 1,
                source.getCanonicalPath().length()));
        if (source.isDirectory())
        {
            String name = source2.getPath().replace("\\", "/");
            if (!name.isEmpty())
            {
                if (!name.endsWith("/"))
                    name += "/";
                JarEntry entry = new JarEntry(name);
                entry.setTime(source.lastModified());
                target.putNextEntry(entry);
                target.closeEntry();
            }
            for (File nestedFile : source.listFiles())
                add(nestedFile, target, removeme);
            return;
        }

        JarEntry entry = new JarEntry(source2.getPath().replace("\\", "/"));
        entry.setTime(source.lastModified());
        target.putNextEntry(entry);
        in = new BufferedInputStream(new FileInputStream(source));

        byte[] buffer = new byte[2048];
        while (true)
        {
            int count = in.read(buffer);
            if (count == -1)
                break;
            target.write(buffer, 0, count);
        }
        target.closeEntry();
    }
    finally
    {
        if (in != null)
            in.close();
    }
}

1 Ответ

2 голосов
/ 15 февраля 2012

Чтобы получить относительный путь, вы должны указать относительный путь при вызове JarEntry (name). Попробуйте удалить часть пути до родительского каталога. Так что это будет что-то вроде

File parentDir = "src";//dir from which you want the relative path

String relPath = source.getCanonicalPath()
                  .substring(parentDir.getCanonicalPath().length() + 1,
                             source.getCanonicalPath().length());

JarEntry entry = new JarEntry(relPath.replace(("\\", "/"));
...
...