我应该如何将文件加载到我的 Java 应用程序中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How should I load files into my Java application?
提问by Will
How should I load files into my Java application?
我应该如何将文件加载到我的 Java 应用程序中?
回答by Will
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()
方法Class
。这使得应用程序更加便携。它可以移动到不同的平台、机器或目录,并且仍然可以正常运行。
回答by Mike Stone
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").
此外,可以使用File.separator、File.separatorChar或System.getProperty("file.separator")解决有关分隔符的平台依赖性。
回答by McDowell
I haven't had a problem just using unix-style path separators, even on Windows (though it is good practice to check File.separatorChar).
即使在 Windows 上使用 unix 样式的路径分隔符也没有问题(尽管检查File.separatorChar是一个好习惯)。
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")目录中的某个位置。)
回答by Vinnie
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
- If configuration, then you can use a ResourceBundleor Spring(if your configuration is more complex).
- 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 usingfile.readLine();
Don't forget to close the file.
- 如果作为资源,请遵循Will 和 Justin给出的建议和示例
- 如果是配置,那么您可以使用ResourceBundle或Spring(如果您的配置更复杂)。
- 如果您需要读取文件以处理其中的数据,此代码片段可能会有所帮助
BufferedReader file = new BufferedReader(new FileReader(filename))
,然后使用file.readLine();
不要忘记关闭文件读取文件的每一行。
回答by cibercitizen1
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;
} // ()
回答by Fridjato Part Fridjat
public static String loadTextFile(File f) {
try {
BufferedReader r = new BufferedReader(new FileReader(f));
StringWriter w = new StringWriter();
try {
String line = reader.readLine();
while (null != line) {
w.append(line).append("\n");
line = r.readLine();
}
return w.toString();
} finally {
r.close();
w.close();
}
} catch (Exception ex) {
ex.printStackTrace();
return "";
}
}