【问题标题】:How to Read a File From Any Computer (Java)如何从任何计算机读取文件 (Java)
【发布时间】:2015-09-25 19:53:27
【问题描述】:

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

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 并将其提供给其他人,该程序将无法运行,因为类路径特定于我的计算机。如何更改访问文件/图像的方式以使其在所有计算机上都可以使用?

【问题讨论】:

标签: java file classpath bufferedimage


【解决方案1】:

特别是对于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 文件中,也可以使用这种方法,与您的类一起(或不)。

【讨论】:

    【解决方案2】:

    您可以在项目中添加一个名为 files 或任何您想要的文件夹。您可以在其中创建子目录并在其中排列文件。当您与他人共享时,它们将可用。在下面的代码中," 。”代表工作目录。所以请确保您提供的目录结构是正确的。试试这样的。

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

    另见

    【讨论】:

    • 从相对于. 的路径读取容易出错。整个 VM 对当前工作目录(即.)只有一种感觉,它与任何给定类或资源文件的位置不一定有任何特定关系。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 1970-01-01
    相关资源
    最近更新 更多