我正在创建一个Java应用程序,我正在使用log4j.我已经给出了配置log4j文件的绝对路径以及生成的日志文件的绝对路径(生成此日志文件的位置).我可以在运行时通过以下方式获取Java Web应用程序的绝对路径:
String prefix = getServletContext().getRealPath("/");
Run Code Online (Sandbox Code Playgroud)
但在普通Java应用程序的上下文中,我们可以使用什么?
Qwe*_*rky 48
尝试;
String path = new File(".").getCanonicalPath();
Run Code Online (Sandbox Code Playgroud)
use*_*421 30
目前尚不清楚你的要求是什么.我不知道'对于我们正在使用的Web应用程序' getServletContext().getRealPath()是什么意思,如果不是答案,但是:
System.getProperty("user.dir")System.getProperty("user.home")this.getClass().getProtectionDomain().getCodeSource().getLocation().由于 a 的应用程序路径JAR和从 an 内部运行的应用程序路径IDE不同,我编写了以下代码以始终返回正确的当前目录:
import java.io.File;
import java.net.URISyntaxException;
public class ProgramDirectoryUtilities
{
private static String getJarName()
{
return new File(ProgramDirectoryUtilities.class.getProtectionDomain()
.getCodeSource()
.getLocation()
.getPath())
.getName();
}
private static boolean runningFromJAR()
{
String jarName = getJarName();
return jarName.contains(".jar");
}
public static String getProgramDirectory()
{
if (runningFromJAR())
{
return getCurrentJARDirectory();
} else
{
return getCurrentProjectDirectory();
}
}
private static String getCurrentProjectDirectory()
{
return new File("").getAbsolutePath();
}
private static String getCurrentJARDirectory()
{
try
{
return new File(ProgramDirectoryUtilities.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParent();
} catch (URISyntaxException exception)
{
exception.printStackTrace();
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
只需打电话getProgramDirectory(),无论哪种方式都应该很好。