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

时间:2023-01-13 21:10:22

How should I load files into my Java application?

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

5 个解决方案

#1


52  

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.

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

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.

相反,在类中使用getResource()方法。这使得应用程序更具有可移植性。它可以移动到不同的平台、机器或目录,并且仍然可以正常工作。

#2


8  

getResource is fine, but using relative paths will work just as well too, as long as you can control where your working directory is (which you usually can).

getResource很好,但是使用相对路径也同样有效,只要可以控制工作目录的位置(通常可以)。

Furthermore the platform dependence regarding the separator character can be gotten around using File.separator, File.separatorChar, or System.getProperty("file.separator").

此外,还可以利用文件实现对分离字符的平台依赖性。分隔符,文件。separatorChar或System.getProperty(“file.separator”)。

#3


7  

What are you loading the files for - configuration or data (like an input file) or as a resource?

您正在为配置或数据(如输入文件)或作为资源加载文件?

  • If as a resource, follow the suggestion and example given by Will and Justin
  • 如果作为一种资源,请遵循Will和Justin给出的建议和例子
  • If configuration, then you can use a ResourceBundle or Spring (if your configuration is more complex).
  • 如果是配置,那么可以使用ResourceBundle或Spring(如果配置更复杂)。
  • If you need to read a file in order to process the data inside, this code snippet may help BufferedReader file = new BufferedReader(new FileReader(filename)) and then read each line of the file using file.readLine(); Don't forget to close the file.
  • 如果您需要读取一个文件来处理内部的数据,这个代码片段可以帮助BufferedReader file = new BufferedReader(新的文件阅读器(文件名)),然后使用file. readline()读取文件的每一行;不要忘记关闭文件。

#4


2  

I haven't had a problem just using unix-style path separators, even on Windows (though it is good practice to check File.separatorChar).

我还没有遇到过使用unix风格的路径分隔符的问题,即使是在Windows上也没有问题(尽管检查文件.分隔符是很好的做法)。

The technique of using ClassLoader.getResource() is best for read-only resources that are going to be loaded from JAR files. Sometimes, you can programmatically determine the application directory, which is useful for admin-configurable files or server applications. (Of course, user-editable files should be stored somewhere in the System.getProperty("user.home") directory.)

使用ClassLoader.getResource()的技术最适合从JAR文件加载的只读资源。有时,您可以通过编程确定应用程序目录,这对于管理可配置文件或服务器应用程序非常有用。(当然,用户可编辑的文件应该存储在System.getProperty(“user.home”)目录中的某个位置。)

#5


2  

public byte[] loadBinaryFile (String name) {
    try {

        DataInputStream dis = new DataInputStream(new FileInputStream(name));
        byte[] theBytes = new byte[dis.available()];
        dis.read(theBytes, 0, dis.available());
        dis.close();
        return theBytes;
    } catch (IOException ex) {
    }
    return null;
} // ()

#1


52  

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.

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

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.

相反,在类中使用getResource()方法。这使得应用程序更具有可移植性。它可以移动到不同的平台、机器或目录,并且仍然可以正常工作。

#2


8  

getResource is fine, but using relative paths will work just as well too, as long as you can control where your working directory is (which you usually can).

getResource很好,但是使用相对路径也同样有效,只要可以控制工作目录的位置(通常可以)。

Furthermore the platform dependence regarding the separator character can be gotten around using File.separator, File.separatorChar, or System.getProperty("file.separator").

此外,还可以利用文件实现对分离字符的平台依赖性。分隔符,文件。separatorChar或System.getProperty(“file.separator”)。

#3


7  

What are you loading the files for - configuration or data (like an input file) or as a resource?

您正在为配置或数据(如输入文件)或作为资源加载文件?

  • If as a resource, follow the suggestion and example given by Will and Justin
  • 如果作为一种资源,请遵循Will和Justin给出的建议和例子
  • If configuration, then you can use a ResourceBundle or Spring (if your configuration is more complex).
  • 如果是配置,那么可以使用ResourceBundle或Spring(如果配置更复杂)。
  • If you need to read a file in order to process the data inside, this code snippet may help BufferedReader file = new BufferedReader(new FileReader(filename)) and then read each line of the file using file.readLine(); Don't forget to close the file.
  • 如果您需要读取一个文件来处理内部的数据,这个代码片段可以帮助BufferedReader file = new BufferedReader(新的文件阅读器(文件名)),然后使用file. readline()读取文件的每一行;不要忘记关闭文件。

#4


2  

I haven't had a problem just using unix-style path separators, even on Windows (though it is good practice to check File.separatorChar).

我还没有遇到过使用unix风格的路径分隔符的问题,即使是在Windows上也没有问题(尽管检查文件.分隔符是很好的做法)。

The technique of using ClassLoader.getResource() is best for read-only resources that are going to be loaded from JAR files. Sometimes, you can programmatically determine the application directory, which is useful for admin-configurable files or server applications. (Of course, user-editable files should be stored somewhere in the System.getProperty("user.home") directory.)

使用ClassLoader.getResource()的技术最适合从JAR文件加载的只读资源。有时,您可以通过编程确定应用程序目录,这对于管理可配置文件或服务器应用程序非常有用。(当然,用户可编辑的文件应该存储在System.getProperty(“user.home”)目录中的某个位置。)

#5


2  

public byte[] loadBinaryFile (String name) {
    try {

        DataInputStream dis = new DataInputStream(new FileInputStream(name));
        byte[] theBytes = new byte[dis.available()];
        dis.read(theBytes, 0, dis.available());
        dis.close();
        return theBytes;
    } catch (IOException ex) {
    }
    return null;
} // ()