【发布时间】:2021-02-02 10:49:57
【问题描述】:
我有一个 Jar 文件,里面有很多 Excel 表格。我想在运行 Jar 文件时访问 excels 表并复制到某处。我该怎么做?
【问题讨论】:
我有一个 Jar 文件,里面有很多 Excel 表格。我想在运行 Jar 文件时访问 excels 表并复制到某处。我该怎么做?
【问题讨论】:
您可以将 Excel 工作表作为类路径中的资源访问:
Class.getResourceAsStream("/excelfiles/myfile.xlsx");
要阅读 Java 中的 Excel 表格,您可以使用 Apache POI 库
如果您只想将文件复制到输出文件夹(不了解 Excel,您可以将资源读取为 InputStream 并将其写入 FileOutputStream。
【讨论】:
问题已解决。我使用下面的代码来访问 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();
}
}
}
【讨论】: