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

qojgxg4l  于 2021-07-08  发布在  Java
关注(0)|答案(2)|浏览(398)

我需要上传一个文件夹的总和x的.png文件,并保存到一个hashmap他们。我怎样才能做到这一点。我的想法是

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

问题是,一开始我的hashmap包含0项,因此它将始终保持为0。如果我不知道我的文件夹里有多少个.png文件,我怎么能把.png文件添加到我的hashmap中呢。
另一个问题是,我使用的是fileinputstream,需要知道.png文件的确切“名称”。我怎样才能知道有多少.png文件,并上传到我的hashmap而不需要知道它们的确切文件名?

m1m5dgzv

m1m5dgzv1#

您只需列出文件夹的内容并找到匹配的文件名。e、 g.使用 java.nio api并将图像放入列表中:

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

还是用旧的 java.io 应用程序编程接口:

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

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

展开查看全部
rxztt3cl

rxztt3cl2#

如果有帮助的话,您可以使用filechooser手动选择文件(比如使用gui),然后将它们加载到列表中,这样从列表到Map就更容易了?

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

  1. //Setting initial directory (finds current system user)
  2. File initialDirectory;
  3. String user = System.getProperty("user.name"); //platform independent
  4. List<File> selectedFiles;
  5. try {
  6. initialDirectory = new File("C:\\Users\\" + user + "\\Pictures" );
  7. fileChooser.setInitialDirectory(initialDirectory);
  8. selectedFiles = fileChooser.showOpenMultipleDialog(Main.stage);
  9. } catch(Exception e) {
  10. initialDirectory = new File("C:\\Users\\" + user);
  11. fileChooser.setInitialDirectory(initialDirectory);
  12. selectedFiles = fileChooser.showOpenMultipleDialog(Main.stage);
  13. }
展开查看全部

相关问题