java - 将 java.nio.file.Path 转换为 File 失败
问题描述
我正在尝试将 .cer 文件打包在一个 jar 中,并使用 java 将它们动态安装到密钥库。
private List<File> doSomething(Path p) {
List<java.io.File>FileList=new ArrayList<>();
try {
int level = 1;
if (p.toString().equals("BOOT-INF/classes/certs")) {
level = 2;
Stream<Path> walk = Files.walk(p, level);
for (Iterator<Path> it = walk.iterator(); it.hasNext(); ) {
System.out.println(it.next());//getting all .cer files in the folder
FileList.add(it.next().toFile());//getting an error UnsupportedOperationException Path not associated with
}
logger.info("fileList" + FileList.size());
}
}
catch(Exception e)
{
logger.error("error-----------"+e);
}
return FileList;
}
我在 toFile() 中收到UnsupportedOperationException,相信这是因为我试图访问 jar 中的文件。有什么方法可以将此 Path(nio.file.Path) 转换为实际文件或流?
解决方案
Path#toString()不会像您要比较的字符串路径一样返回带有正斜杠 ( / ) 的路径。它用反斜杠(\)返回它,因此您的比较永远不会成为真的。
从本地文件系统读取路径时,始终使用与系统相关的路径或文件分隔符。为此,您可以使用String#replaceAll()方法将任何路径名斜杠转换为适合您的代码正在运行的文件系统的内容,例如:
String pathToCompare = "BOOT-INF/classes/certs"
.replaceAll("[\\/]", "\\" + File.separator);
这应该可以正常工作:
private List<java.io.File> doSomething(java.nio.file.Path p) {
java.util.List<java.io.File> FileList = new java.util.ArrayList<>();
try {
int level = 1;
String pathToCompare = "BOOT-INF/classes/certs"
.replaceAll("[\\/]", "\\" + File.separator);
if (p.toString().equals(pathToCompare)) {
level = 2;
java.util.stream.Stream<Path> walk = java.nio.file.Files.walk(p, level);
for (java.util.Iterator<Path> it = walk.iterator(); it.hasNext();) {
System.out.println(it.next());//getting all .cer files in the folder
FileList.add(it.next().toFile());//getting an error UnsupportedOperationException Path not associated with
}
}
}
catch (Exception e) {
System.err.println(e);
}
return FileList;
}
编辑:
如果您想根据特定的文件扩展名和/或 JAR 文件的内容列出您的列表,那么您需要做一些不同的事情。下面的代码与您一直在使用的代码非常相似,不同之处在于:
- 方法名称更改为getFilesList();
- 列表返回为
List<String>
而不是List<File>
; - 深度级别现在是提供给方法的参数(始终确保深度级别足以执行任务);
- 该方法中添加了一个可选的 String args 参数(名为:)
onlyExtensions
,以便可以应用一个(或多个)文件扩展名来返回一个列表,该列表仅包含文件名包含所应用扩展名的路径。如果提供的扩展恰好是,".jar"
那么该 JAR 文件的内容也将应用于返回的列表。如果未提供任何内容,则列表中将返回所有文件。
对于 JAR 文件,还提供了一个辅助方法:
修改任何您认为合适的代码:
public static List<String> getFilesList(String thePath, int depthLevel, String... onlyExtensions) {
Path p = Paths.get(thePath);
java.util.List<String> FileList = new java.util.ArrayList<>();
try {
java.util.stream.Stream<Path> walk = java.nio.file.Files.walk(p, depthLevel);
for (java.util.Iterator<Path> it = walk.iterator(); it.hasNext();) {
File theFile = it.next().toFile();
if (onlyExtensions.length > 0) {
for (String ext : onlyExtensions) {
ext = ext.trim();
if (!ext.startsWith(".")) {
ext = "." + ext;
}
if (!theFile.isDirectory() && theFile.getName().substring(theFile.getName().lastIndexOf(".")).equalsIgnoreCase(ext)) {
FileList.add(theFile.getName() + " --> " + theFile.getAbsolutePath());
}
else if (!theFile.isDirectory() && theFile.getName().substring(theFile.getName().lastIndexOf(".")).equalsIgnoreCase(".jar")) {
List<String> jarList = getFilesNamesFromJAR(theFile.getAbsolutePath());
for (String strg : jarList) {
FileList.add(theFile.getName() + " --> " + strg);
}
}
}
}
else {
FileList.add(theFile.getAbsolutePath());
}
}
}
catch (Exception e) {
System.err.println(e);
}
return FileList;
}
JAR 文件辅助方法:
public static java.util.List<String> getFilesNamesFromJAR(String jarFilePath) {
java.util.List<String> fileNames = new java.util.ArrayList<>();
java.util.zip.ZipInputStream zip = null;
try {
zip = new java.util.zip.ZipInputStream(new java.io.FileInputStream(jarFilePath));
for (java.util.zip.ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
fileNames.add(entry.getName());
}
}
catch (java.io.FileNotFoundException ex) {
System.err.println(ex);
}
catch (java.io.IOException ex) {
System.err.println(ex);
}
finally {
try {
if (zip != null) {
zip.close();
}
}
catch (IOException ex) {
System.err.println(ex);
}
}
return fileNames;
}
要使用getFileList()方法,您可以执行以下操作:
List<String> fileNames = getFilesList("C:\\MyDataFolder", 3, ".cer", ".jar");
// Display files in fileNames List
for (String str : fileNames) {
System.out.println(str);
}
推荐阅读
- sql-server - 删除 nvarchar SQL 中逗号后的最后一个值
- python - python中如何使用TypeVar进行多个通用协议的输入和输出?
- vb.net - 可以从 CrystalReport 读取数据吗?
- azure - 在 CI 管道中运行时赛普拉斯测试花费的时间太长
- python - Pyqt5 - 放大 QLabel
- laravel - Laravel Blade 显示带有星号和变量索引的错误消息
- python - 读取文件返回单词和空格 python
- android - Android 是否可以在回收站视图中滑动部分元素?
- python - BeautifulSoup 和 Gadget Selector 用于抓取表格
- python - 是否可以读取位于 python 项目中的 csv 文件?