java读取linux文件,如何在Windows和Linux上从Java读取文件

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.

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.

But my application can not find the file specified in /XML/RequestXML/ in linux environment.

If I change the file path as /usr/XML/RequestXML/ it works in linux.

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

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());

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值