如何在Windows和Linux上从Java读取文件 [英] How to read file on Windows and Linux from Java
问题描述
我在D:\XML\RequestXML
中有一个xml文件,我正在从FileReader
中读取此文件夹中的xml文件.在我的程序中,我对文件路径/XML/RequestXML/
进行了硬编码.在windows
环境下可以正常工作.在Windows中,JBoss
在D:\jbossdistrib\jboss
中.
I have a xml file located in D:\XML\RequestXML
and I am reading xml file in this folder from a FileReader
. In my program I hard coded the file path /XML/RequestXML/
. This works fine with the windows
environment. In windows JBoss
is in D:\jbossdistrib\jboss
.
我在linux
/usr/XML/RequestXML/
中创建了文件夹结构.并将xml添加到RequestXML文件夹中. JBoss
在/usr/jbossdistrib/jboss/
路径中.
I created the folder structure in linux
/usr/XML/RequestXML/
. And add the xml in to RequestXML folder. JBoss
is in /usr/jbossdistrib/jboss/
path.
但是我的应用程序找不到在Linux环境中的/XML/RequestXML/中指定的文件.
But my application can not find the file specified in /XML/RequestXML/ in linux environment.
如果我将文件路径更改为/usr/XML/RequestXML/
,那么它将在Linux中工作.
If I change the file path as /usr/XML/RequestXML/
it works in linux.
如何在linux和Windows中都使用一致的文件路径?
How can I use the consistent file path in linux and windows both?
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();
}
}
更新
Update
我的问题是如何在不使用/usr/
的情况下设置文件路径,而在Windows中可以正常使用.
如果这不可能,那么我是否还需要在Windows环境中将路径用作/usr/XML/RequestXML/
?所以我必须在Windows中创建一个类似于D:\usr\XML\RequestXML
的文件夹结构.
My question is how to set the file path without /usr/
which works fine in Windows.
If this is not possible, then do I need to use the path as /usr/XML/RequestXML/
in windows environment as well? so I have to create a folder structure like D:\usr\XML\RequestXML
in windows.
推荐答案
如果您知道当前的工作目录(请使用以下命令进行测试:
If you know the current working directory (test it with:
System.out.println(new File(".").getAbsolutePath());
您可以对../../XML/RequestXML之类的相对目录进行硬编码
you can hardcode a relative directory like ../../XML/RequestXML
记录:尽管这可能有所帮助,但我仍然相信您应该尝试使用配置参数或通过将其作为类路径中可用的资源加载来解决此问题.
For the record: although this may help, I still believe you should try to solve this with a configuration parameter or by loading it as a resource available in the classpath.
这篇关于如何在Windows和Linux上从Java读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!