【问题标题】:How to access the excels sheets while running the Jar file inside it and copy outside jar?如何在其中运行 Jar 文件并复制外部 jar 时访问 excels 表?
【发布时间】:2021-02-02 10:49:57
【问题描述】:

我有一个 Jar 文件,里面有很多 Excel 表格。我想在运行 Jar 文件时访问 excels 表并复制到某处。我该怎么做?

【问题讨论】:

    标签: java file jar


    【解决方案1】:

    您可以将 Excel 工作表作为类路径中的资源访问:

    Class.getResourceAsStream("/excelfiles/myfile.xlsx");
    

    要阅读 Java 中的 Excel 表格,您可以使用 Apache POI

    如果您只想将文件复制到输出文件夹(不了解 Excel,您可以将资源读取为 InputStream 并将其写入 FileOutputStream

    【讨论】:

    • 我的问题是一个带有子文件夹的文件夹中有 100 个 excel 文件(比如“excelFolder”),我需要获取所有 excel 文件的名称。我无法对 excel 文件名进行硬编码.
    • 这可能有助于:stackoverflow.com/questions/3923129/… 扫描类路径文件夹中的资源。
    【解决方案2】:

    问题已解决。我使用下面的代码来访问 jar 内的 excel,并在我的 Jar 外复制 excel

    public static void main(String[] args) throws IOException {
        final String classPath = "Path_Of_Jar/abc.jar";
        JarFile jarFile = new JarFile (classPath);
    
        String copyFolderExcel="Path to copy excels";
        File excelFolderFile = new File (copyFolderExcel);
        excelFolderFile.mkdir();
    
        Enumeration<JarEntry> e = jarFile.entries ();
        while (e.hasMoreElements ()) {
            JarEntry entry = (JarEntry) e.nextElement ();
    
            if (entry.getName ().contains ("excelFiles/")) {
                String name = entry.getName ();
    
                if(name.contains (".xlsx")) {
                    copyExcel(jarFile,name,copyFolderExcel);
    
                }
          }
        }
    jarFile.close ();
    }
    
    private static void copyExcel(JarFile jarFile, String file,String updatedFolder) throws IOException {
    
    
        String[] outputFileName = file.split ("/");
        String finalName = outputFileName[outputFileName.length-1];
    
        JarEntry entry = (JarEntry) jarFile.getEntry(file);
        InputStream input = jarFile.getInputStream(entry);
        OutputStream output = new FileOutputStream (updatedFolder+"/"+finalName);
    
    
        try {
            byte[] buffer = new byte[input.available ()];
            for (int i = 0; i != -1; i = input.read (buffer)) {
                output.write (buffer, 0, i);
            }
        } finally {
    
            input.close();
            output.close();
        }
    }
    

    }

    【讨论】:

      猜你喜欢
      • 2019-05-21
      • 2013-06-08
      • 2016-09-30
      • 2011-09-18
      • 1970-01-01
      • 2020-02-22
      • 2014-07-30
      • 2010-10-02
      • 1970-01-01
      相关资源
      最近更新 更多