上传一组.png文件并保存到HashMap中



我需要上传一个包含.png文件总数x的文件夹,并将它们保存到哈希图中。我怎样才能做到这一点。我的想法是

HashMap<Integer,Image> map = new HashMap<>();
for (int i= map.size();map>0;map-- ){
map.put(i, new Image(new FileInputStream("C:\Users\drg\Documents\image"+i+".png")));
}

问题是,一开始我的HashMap包含0个项,因此它将始终保持为0。那么,如果我不知道文件夹中有多少.png文件,我该如何将.png文件添加到我的HashMap中呢。

另一个问题是,我正在使用FileInputStream;name";.png文件的。我如何在不需要知道确切文件名的情况下找出有多少.png文件并将其上传到我的HashMap中?

您所需要做的就是列出文件夹的内容并找到匹配的文件名。例如,使用java.nioAPI并将图像放入列表:

Path folder = FileSystems.getDefault().getPath("Users", "drg", "Documents");
List<Image> images = Files.list(folder)
.filter(path -> path.getFileName().toString().matches("image\d+\.png"))
.map(Path::toUri)
.map(URI::toString)
.map(Image::new)
.collect(Collectors.toList());

或者使用旧的java.ioAPI:

File folder = new File("C:/Users/drg/Documents");
File[] imageFiles = folder.listFiles(file -> file.getName().matches("image\d+\.png"));
List<Image> images = new ArrayList<>();
for (File file : imageFiles) {
images.add(new Image(file.toURI().toString()));
}

如果您需要按整数对它们进行索引,那么当您有文件名时,提取该整数值相当容易。

如果有帮助,您可以帮助使用FileChooser手动挑选文件(就像使用GUI一样(,并将它们加载到列表中,然后从列表到映射可能会更容易?

```
private void uploadPhoto() {
FileChooser fileChooser = new FileChooser();
//Sets file extension type filters (Pictures)
fileChooser.getExtensionFilters().addAll
(new FileChooser.ExtensionFilter("Picture Files", "*.jpg", "*.png"));

//Setting initial directory (finds current system user)
File initialDirectory;
String user = System.getProperty("user.name"); //platform independent
List<File> selectedFiles;
try {
initialDirectory = new File("C:\Users\" + user + "\Pictures" );
fileChooser.setInitialDirectory(initialDirectory);  
selectedFiles = fileChooser.showOpenMultipleDialog(Main.stage);
} catch(Exception e) {
initialDirectory = new File("C:\Users\" + user);
fileChooser.setInitialDirectory(initialDirectory);
selectedFiles = fileChooser.showOpenMultipleDialog(Main.stage);
}
```

最新更新