我在D:\XML\RequestXML中有一个xml文件,我从FileReader中读取这个文件夹中的xml文件。在我的程序中,我硬编码了文件路径/XML/RequestXML/。这在windows环境中很好。在windows中,JBoss在D:\jbossdistrib\jboss中。
我在linux /usr/XML/RequestXML/中创建了文件夹结构。并将xml添加到RequestXML文件夹中。JBoss在/usr/jbossdistrib/jboss/路径上。
但是我的应用程序找不到/XML/RequestXML/在linux环境中指定的文件。
如果我将文件路径更改为/usr/XML/RequestXML/,它将在linux中工作。
如何在linux和windows中使用一致的文件路径?
public class Controller extends HttpServlet {
private String filePath = "/XML/RequestXML/";
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String file = request.getParameter("fileName");
xml = readFile(filePath + file);
}
private String readFile(String file) {
StringBuffer fileData = new StringBuffer();
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
char[] buf = new char[1024];
int numRead=0;
while((numRead=reader.read(buf)) != -1){
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
}
catch (FileNotFoundException e) {
logger.fatal("File not found in specifid path "+ file);
}
catch (IOException e) {
logger.fatal("Error while reading the xml file");
}
return fileData.toString();
}
}更新
我的问题是如何在没有/usr/的情况下设置文件路径,这在Windows中很好。如果这是不可能的,那么我是否也需要在windows环境中使用路径作为/usr/XML/RequestXML/呢?因此,我必须在windows中创建一个类似D:\usr\XML\RequestXML的文件夹结构。
发布于 2014-08-14 12:36:39
如果您知道当前的工作目录(用:
System.out.println(new File(".").getAbsolutePath());您可以硬编码一个相对目录,如./../XML/RequestXML
记录在案:尽管这可能会有所帮助,但我仍然认为您应该尝试使用配置参数来解决这个问题,或者将其作为类路径中可用的资源来加载。
发布于 2014-08-14 12:21:30
I don't want two paths
然后将文件放在应用程序的“资源”文件夹中,然后尝试以这种方式读取该文件。
private String filePath = className.getClass()
.getResource("yourFileName").getPath();
BufferedReader reader = new BufferedReader(new FileReader(filePath));发布于 2014-08-14 12:34:48
首先,有一点坏消息: FileReader是一个实用程序类,默认情况下使用平台编码:,不可移植的。由于编码是在XML源本身中定义的,所以如果可能的话,可以保留InputStream。
您可以将XML保留为war/ear中的只读资源。
或者作为应用程序外部jboss目录中的只读资源。通过jboss的系统ClassLoader作为java资源使用。
或者作为文件,其中路径配置如下所示。可能在现有的属性/xml配置文件中。您还可以使用jboss管理控制台来配置路径。
可能令人感兴趣:
System.getProperty("file.encoding"); // The default encoding
System.getProperty("user.name"); // Under which user are we running
System.getProperty("user.home"); // The user's home
System.getProperty("user.dir"); // The applications working dirJBoss还定义了一些东西,但这是不可移植的。
https://stackoverflow.com/questions/25307720
复制相似问题