简体   繁体   English

Java相当于Ruby的__FILE__?

[英]Java's equivalent of Ruby's __FILE__?

In Ruby I frequently use File.dirname(__FILE__) to open configuration files and such. 在Ruby中,我经常使用File.dirname(__FILE__)打开配置文件等。 For those that don't know Ruby, this will give the location on the file system of the file it's called from. 对于不了解Ruby的用户,这将提供从中调用文件的文件在文件系统中的位置。 This allows me to package libraries with data and config files and open those files with relative paths. 这使我可以将包含数据和配置文件的库打包,并使用相对路径打开这些文件。

What's the Java equivalent of this? Java的等效功能是什么? If there is a data file I want to package with a jar how would I open the data file from Java code that is also in the jar? 如果有一个数据文件,我想用一个jar打包,我该如何从同样在jar中的Java代码打开数据文件?

The equivalent API in Java is getResourceAsStream . Java中的等效API是getResourceAsStream This will open a stream to a file stored in the JAR relative to the class on which it is invoked. 这将打开一个流,该流指向存储在JAR中的文件(相对于调用它的类)。

There are variants, such as getResource , which returns a URL, or methods on ClassLoader that use an absolute path inside the JAR file. 有多种变体,例如getResource (返回URL),或ClassLoader上的方法使用JAR文件中的绝对路径。

Please see Java Applications and the "Current Directory" : 请参阅Java应用程序和“当前目录”

In Java, you use File objects to construct a relative view of the file system. 在Java中,您可以使用File对象来构造文件系统的相对视图。 Two of the constructors for the File object take a 'parent' argument that specifies a parent path that is prefixed to the path of the file itself to create the full abstract path to the file. File对象的两个构造函数带有一个“ parent”参数,该参数指定一个父路径,该父路径以文件本身的路径为前缀,以创建该文件的完整抽象路径。 What you do is, create a File object with the path that represents your current directory and then create all your file objects using that File object as the parent. 您要做的是,使用代表当前目录的路径创建一个File对象,然后使用该File对象作为父对象来创建所有文件对象。 Voila, a current directory. Voila,当前目录。

Also I would recommend Reading and Writing a Properties File : 我也建议阅读和写入属性文件

// Read properties file.
Properties properties = new Properties();
try {
    properties.load(new FileInputStream("filename.properties"));
} catch (IOException e) {
}

// Write properties file.
try {
    properties.store(new FileOutputStream("filename.properties"), null);
} catch (IOException e) {
}

I voted for @andrew, but I'd like to point out that in Java, the directory the file itself is pretty meaningless except for a few highly reflective (and most likely wrong) purposes. 我对@andrew投了赞成票,但我想指出的是,在Java中,文件目录本身是毫无意义的,除了一些具有高度反射性(很可能是错误的)的目的。

It will be in a directory based on a package structure, and could be located in a jar or pretty much anywhere. 它将位于基于包结构的目录中,并且可以位于jar或几乎任何位置。

Java's a little less ad-hock, allowing for less shortcuts, but usually improving consistency and reliability at deployment time. Java的ad-hock少了一点,允许更少的快捷方式,但是通常可以在部署时提高一致性和可靠性。

如果仅指定文件名,那么JVM将在启动应用程序的同一目录中查找该文件(不一定是应用程序所在的目录)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM