簡體   English   中英

從Java項目資源復制目錄和文件

[英]Copy directory and files from java project resource

我需要將位於java項目中的目錄“ src”作為公共資源進行復制。 此“ src”文件夾包含其他子文件夾和文件,因此我也需要復制它們。 我如何實現這樣的目標? 我面臨的主要問題是我無法檢索“ src”文件夾的絕對路徑。 一個解決方案是逐個文件復制,但是它們太多了,我想找到一個更好的解決方案

謝謝

編輯:當用戶單擊“生成”按鈕時,我的應用程序向用戶詢問生成某些文件的目標位置。 我要在此目標位置復制“ src”文件夾及其所有子文件夾。 上面很難過,“ src”文件夾位於我的Java項目主文件夾中。

如果要從jar文件中提取源代碼,可以從以下簡短示例開始

public class UnZip {

    public static void main(String argv[]) {
        String destDir = "/tmp/";
        String sourceJar = "your_src.jar";

        try (ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(sourceJar)))) {
            ZipEntry zipEntry;
            while ((zipEntry = zis.getNextEntry()) != null) {
                File newDestination = new File(destDir + zipEntry.getName());
                if (zipEntry.isDirectory()) {
                    unzipDir(newDestination);
                } else {
                    unzipFile(newDestination, zis);
                }
            }
        } catch (IOException ex) {
            System.err.println("input file coud not be read " + ex.getMessage());
        }
    }

    private static void unzipFile(File file, final ZipInputStream zis) {
        System.out.printf("extract to: %s - ", file.getAbsoluteFile());
        if (file.exists()) {
            System.out.println("already exist");
            return;
        }
        int count;
        try (BufferedOutputStream dest = new BufferedOutputStream(new FileOutputStream(file), BUFFER_SIZE)) {
            while ((count = zis.read(BUFFER, 0, BUFFER_SIZE)) != -1) {
                dest.write(BUFFER, 0, count);
            }
            dest.flush();
            System.out.println("");
        } catch (IOException ex) {
            System.err.println("file could not be created " + ex.getMessage());
        }
    }

    private static void unzipDir(File dir) {
        System.out.printf("create directory: %s - ", dir);
        if (dir.exists()) {
            System.out.println("already exist");
        } else if (dir.mkdirs()) {
            System.out.println("successful");
        } else {
            System.out.println("failed");
        }
    }

    static final int BUFFER_SIZE = 2048;
    static byte[] BUFFER = new byte[BUFFER_SIZE];
}

我解決了創建需要生成的應用程序的zip存檔的問題。 然后從我的項目中解壓縮從資源文件夾中獲取的存檔,然后打開需要修改的Java文件流,然后對其進行編輯。 這是代碼,類似於SubOptimal的解決方案

UnzipUtility unzipper = new UnzipUtility();
InputStream inputStream = getClass()
        .getResource("/template/template.zip").openConnection()
        .getInputStream();
unzipper.unzip(inputStream, parentFolder.getCanonicalPath());

UnzipUtility類來自以下示例: http : //www.codejava.net/java-se/file-io/programmatically-extract-a-zip-file-using-java

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM