Java相对文件路径 [英] Java relative file paths

查看:67
本文介绍了Java相对文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个我一直在困扰的Java问题:什么是指示相对文件路径的好方法.

I've got a Java question that I've been having a trouble with: what is a good way to indicate relative file paths.

让我更具体一些.我想可以说总是在./configuration/file.txt中查找配置文件.我遇到的问题是,我的程序只有从文件所在的目录中启动,才能正常运行.如果相反,我是从另一个目录(如./directory/to/my/program/execute.sh)启动,则它将无法正常运行.

Let me be more specific. I want to be able to say to always look for configuration files in ./configuration/file.txt. The problem I'm having is that my program will only work correctly if it is started from the directory the file is in. If instead I start it from a different directory like ./directory/to/my/program/execute.sh then it fails to function correctly.

但是我还需要对此文件进行更改,并且资源似乎希望是只读的...

But I also need to make changes to this file, and resources seem to want to be read-only...

推荐答案

读取配置信息的建议方式(使该应用独立于特定于环境的详细信息)是将其作为 classpath资源读取而不是文件系统资源.阅读智能加载属性更多细节.

The suggested (so that the app is independent of the environment specific details) way to read configuration information is to read it as a classpath resource rather than a file system resource. Read Smartly load your properties for more details.

阅读 Class.getResourceAsStream javadoc 获取有关如何指定资源路径的语法

Read Class.getResourceAsStream javadoc for syntax on how to specify the resource path

关于SO的有用文章: jar中的类路径资源

Useful post on SO: Classpath resource within jar

这篇关于Java相对文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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