如何从任何计算机读取文件 (Java)

How to Read a File From Any Computer (Java)

目前我的程序中有这样的代码:

BufferedImage ReadPicture = null;
            try {
                ReadPicture = ImageIO.read(new File("C:/Users/John/Documents/NetBeansProjects/Program5/build/classes/Program5/Pictures/TestPicture.png"));
            } catch (IOException e) {
            }

如果我将我的文件编译成 jar 文件并将其提供给其他人,该程序将无法运行,因为类路径是特定于我的计算机的。我怎样才能改变我访问 files/images 的方式,以便它在所有计算机上工作?

您可以在您的项目中添加一个名为 files 的文件夹或您 want.You 可以在其中创建子目录并在 that.They 中安排文件的任何内容,当您将其共享给 others.In 下面的代码,"."代表工作 directory.So 确保您提供的目录结构是 correct.Try 类似这样的东西。

BufferedImage ReadPicture = null;
try {
         ReadPicture = ImageIO.read(new File("./files/Pictures/TestPicture.png"));

     } catch (IOException e) {
     }

另请参阅

  • Java Project Folder Structure

对于 ImageIO 特别是,如果您总是想从类路径 中读取图像 ,而不考虑类路径实际是什么,那么您可以这样做:

BufferedImage readPicture = null;
URL imageUrl = getClass().getClassLoader().getResource(
        "/Program5/files/Pictures/TestPicture.png");
// Or
// InputStream imageStream = getClass().getClassLoader().getResourceAsStream(
//         "/Program5/files/Pictures/TestPicture.png");

// null if not found

try {
    readPicture = ImageIO.read(imageUrl);
    // null if the image format is unrecognized
} catch (IOException e) {
    // ...
}

这依赖于 ImageIO 可以通过 URL 获取图像这一事实。即使图像与您的 类(或不)一起打包在 Jar 文件中,也可以使用此方法。