简体   繁体   English

如何在Web应用程序中的Java Bean中指定文件路径?

[英]How to specify file path in Java Bean in a web application?

I want to read models.txt in WebContent/resources/db/ from IndexBean.java in src/DataTable/. 我想读的WebContent /资源/ DB /从IndexBean.java在SRC / DataTable中/ models.txt。 How shall I set the filePath in 我应该如何设置filePath

sc = new Scanner(new File(filePath));

I know I can achieve this by absolute path, but want to know how to do it in relative path. 我知道我可以通过绝对路径来实现,但是想知道如何在相对路径中做到这一点。

捕获

And another interesting thing is: In IndexBean.java which is a Java Bean , if I run the following code, I will get the path of eclipse.exe. 另一个有趣的事情是:在Java Bean的 IndexBean.java中,如果运行以下代码,则将获得eclipse.exe的路径。 While if I run the same code in testFileRead.java in the same package which is not a Java Bean , I will get the path of the workspace of the application. 如果我在不是Java Bean的同一包中的testFileRead.java中运行相同的代码,则将获取应用程序工作空间的路径。 Could someone explain this? 有人可以解释一下吗? Thanks! 谢谢!

File dir1 = new File("..");
try {
    System.out.println("Current dir : " + dir1.getCanonicalPath());
} catch (IOException e1) {
    e1.printStackTrace();
}

First of all, these kind of internal files should reside in an inaccessible spot, in WebContent/WEB-INF . 首先,这类内部文件应位于WebContent/WEB-INF无法访问的位置。

You could get a file system File: 您可以获得文件系统文件:

File file = request.getServletContext().getRealPath("/resources/db/models.txt");

If you store the file as real resource (in the class path), you can use: 如果将文件存储为真实资源 (在类路径中),则可以使用:

InputStream in = getClass().getResourceAsStream("/db/models.txt");

Please specify the character encoding: 请指定字符编码:

sc = new Scanner(new File(filePath), "UTF-8");

So the same encoding is used whether developing under Windows or deploying on a Linux server. 因此,无论是在Windows下开发还是在Linux服务器上部署,都使用相同的编码。 Because the default encoding is platform dependent. 因为默认编码取决于平台。


ServletContext servletContext = (ServletContext)
    FacesContext.getCurrentInstance().getExternalContext().getContext();

I think @Joop Eggen has proposed the best solution for you. 我认为@Joop Eggen为您提出了最佳解决方案。 However, sometimes you can set a environment variable to your file path and you can change it as you push your code through different environment. 但是,有时您可以将环境变量设置为文件路径,并且可以在通过不同环境推送代码时进行更改。

 String dir = System.getProperty("user.dir");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM