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

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

问题描述

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

How should I load files into my Java application?

推荐答案

简答

使用以下两种方法之一:

Use one of these two methods:

例如:

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

--

长答案

通常情况下,人们不希望使用绝对路径加载文件.例如,如果您能提供帮助,请不要这样做:

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");

不推荐使用这种技术,至少有两个原因.首先,它创建了对特定操作系统的依赖性,这会阻止应用程序轻松迁移到另一个操作系统.Java 的主要优点之一是能够在许多不同的平台上运行相同的字节码.使用这样的绝对路径会使代码的可移植性大大降低.

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).

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

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天全站免登陆