2

这篇文章是我几天前进行的另一项调查的第 2 部分。然后使用此代码,我将放在最后,通过 JButton1,我能够附加一个文件,并使其在应用程序北部和东部的窗口中可见。我现在正在尝试导入:

1) 将新图像放入某个目录,例如放入 C:\output

2)图像的整个目录(文件夹),可以说来自 C:\importImages

进入 C:\output 。

为此,我假设我在 C:\importImages 目录中有一些图像。下面,这些是我需要填写的 2 个代码示例,以便我想要工作。尝试加载目录的第一种方法无法运行。我认为它的错误可能与 GUI Builder 中的 Filechooser 按钮有关。

这是加载整个目录的完整方法。

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:(for importing a whole directory(folder) from C:\importImages into C:\output ).
JFileChooser chooser = new JFileChooser();
        chooser = new JFileChooser(); 

        File f = chooser.getSelectedFile();

        String filename = f.getAbsolutePath();
    try {
        ImageIcon ii=new ImageIcon(scaleImage(250, 250, ImageIO.read(new File(filename))));//get the image from file chooser (directories)
        //jLabel1.setIcon(ii);

        File srcDir = new File(filename);
        File destDir = new File("C:/output/");
        FileUtils.copyDirectoryToDirectory(srcDir, destDir);

    }
        catch (Exception ex) {
        ex.printStackTrace();
    }
    }

以及仅导入单个文件的方法。

  private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here(for importing a single image to directory C:\output ).
--
    }

提前致谢!

4

1 回答 1

0

最好的学习方法,自己尝试。
我可以向你展示可能性。试试这些有用的方法来插入你的代码。

问题:我现在正在尝试导入:

  • 1) 将新图像放入某个目录,例如放入 C:\output

回答:

鉴于 File API 中没有将文件从一个位置复制到另一个位置的直接方法,如何将 Java 中的文件从一个目录复制到另一个目录是常见的要求。

复制文件的一种方法是从 FileInputStream 读取并将相同的数据写入 FileOutputStream 到另一个目录。

值得庆幸的是,您不需要在这里重新发明轮子,有一些可用的开源库允许我们轻松地将 Java 中的文件从一个目录复制到另一个目录。其中一个库是Apache commons IO,它包含一个名为FileUtils的类,它为文件相关操作提供实用方法。

在不同位置复制和重命名文件

FileUtils.copyFile

FileUtils.copyFile(sourceFile, targetFile)可以使用

    String source = "C:/output/myImage.jpg";
    //directory where file will be copied
    String target ="C:/importImages/";

    //name of source file
    File sourceFile = new File(source);
    String Filename = sourceFile.getName();

    File targetFile = new File(target+Filename);

    //copy file from one location to other
    FileUtils.copyFile(sourceFile, targetFile);

问题:我现在正在尝试导入:

  • 2)图像的整个目录(文件夹),可以说从 C:\importImages 到 C:\output 。

回答:

现在用java完成目录迭代的标准方法是什么?

在java中遍历目录的最佳方法?

在您的代码中添加这些方式。是不是很难。

  • 测试文件扩展名 (.jpg .gif ...)
  • 别忘了抓
  • NullPointerException - 如果源或目标为 null
  • IOException - 如果源或目标无效
  • IOException - 如果在复制期间发生 IO 错误
于 2013-01-06T22:18:26.483 回答