我应该如何将文件加载到我的Java应用程序? [英] How should I load files into my Java application?

查看:117
本文介绍了我应该如何将文件加载到我的Java应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将文件加载到我的Java应用程序中?

解决方案

简短的答案 p>

使用以下两种方法之一:





例如:

  InputStream inputStream = YourClass.class.getResourceAsStream image.jpg的); 

-



长回答



通常,不想使用绝对路径加载文件。例如,如果您可以帮助它,请不要这样做:

 文件文件=新文件(C:\\\ \\Users\\Joe\\image.jpg); 

至少有两个原因,不建议使用此技术。首先,它创建了对特定操作系统的依赖,从而防止应用程序轻松移动到另一个操作系统。 Java的主要优点之一是能够在许多不同的平台上运行相同的字节码。使用这样的绝对路径使得代码的便携性更低。



其次,根据文件的相对位置,此技术可能会创建外部依赖关系,并限制应用程序的移动性。如果文件存在于应用程序的当前目录之外,则会创建外部依赖关系,并且必须注意依赖关系以将应用程序移动到另一台机器(容易出错)。



而是使用 Class 类中的 getResource()方法。这使得应用程序更加便携。它可以移动到不同的平台,机器或目录,并仍然可以正常工作。


How should I load files into my Java application?

解决方案

The short answer

Use one of these two methods:

For example:

InputStream inputStream = YourClass.class.getResourceAsStream("image.jpg");

--

The long answer

Typically, one would not want to load files using absolute paths. For example, don’t do this if you can help it:

File file = new File("C:\\Users\\Joe\\image.jpg");

This technique is not recommended for at least two reasons. First, it creates a dependency on a particular operating system, which prevents the application from easily moving to another operating system. One of Java’s main benefits is the ability to run the same bytecode on many different platforms. Using an absolute path like this makes the code much less portable.

Second, depending on the relative location of the file, this technique might create an external dependency and limit the application’s mobility. If the file exists outside the application’s current directory, this creates an external dependency and one would have to be aware of the dependency in order to move the application to another machine (error prone).

Instead, use the getResource() methods in the Class class. This makes the application much more portable. It can be moved to different platforms, machines, or directories and still function correctly.

这篇关于我应该如何将文件加载到我的Java应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆