【问题标题】:How to make the Filepath Generic which suits all OS?如何制作适合所有操作系统的文件路径通用?
【发布时间】:2010-11-02 21:13:22
【问题描述】:
private static final String DESTINATION_DIR_PATH ="/files";
private File destinationDir; 
public void init(ServletConfig config) throws ServletException {
        super.init(config);
        String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
        destinationDir = new File(realPath);
        if(!destinationDir.isDirectory()) {
            throw new ServletException(DESTINATION_DIR_PATH+" is not a directory");
        }

    }

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            PrintWriter out = response.getWriter();
            response.setContentType("text/html");
            out.println();
            DiskFileItemFactory  fileItemFactory = new DiskFileItemFactory ();
            fileItemFactory.setSizeThreshold(1*1024*1024);
            //fileItemFactory.setRepository(tmpDir);
            ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
            try {
                    List items = uploadHandler.parseRequest(request);
                    Iterator itr = items.iterator();
                while(itr.hasNext()) {
                    FileItem item = (FileItem) itr.next();
                    if(item.isFormField()) {
                        out.println("File Name = "+item.getFieldName()+", Value = "+item.getString());
                    } else {
                        File file = new File(destinationDir,item.getName());
                        item.write(file);
                String fileToBeRead = "C:/ProgramFiles/Apache/Tomcat/webapps/Readcsv/files/"+item.getName();
try {
                            BufferedReader br = new BufferedReader(new FileReader(fileToBeRead));..... and the code goes on..

我正在使用上面的代码来读取通过 JSP 表单上传的 .csv 文件。 代码工作得很好。 但我希望代码采用通用格式,因为上述代码仅适用于 Windows 系统,不适用于 UNIX 或任何其他操作系统。

String fileToBeRead = "C:/ProgramFiles/Apache/Tomcat/webapps/Readcsv/files/"+item.getName();

必须更改此特定行以完成任务。请让我知道可以做什么,以便代码在它遍历的任何操作系统中都能正常工作。另外请指出上述代码中需要更改的所有区域。

【问题讨论】:

  • 这段代码的格式非常糟糕,难以阅读。打开 IDE 的格式化程序怎么样?
  • 抱歉,我没有使用任何 IDE。但是要集中的区域是代码的前两行以及我在位置上单独提到的那一行。

标签: java jsp servlets filepath


【解决方案1】:

除了上面的回复之外,在 Servlet 代码中硬编码文件位置并不是一个好的做法,因为当部署在不同的服务器上或直接从压缩的 WAR 文件运行 Web 应用程序时,这通常会导致 Servlet 无法工作。从 Web 应用程序读取资源的正确方法是使用 getResource() 或 getResourceAsStream() 方法。这两种方法确保 Servlet 始终能够访问所需资源,即使 Web 应用程序部署在多个服务器上或作为压缩 WAR 部署。

getResourceAsStream(java.lang.String path):getResourceAsStream() 方法将 InputStream 的实例返回到 Web 应用程序的物理资源。当需要逐字读取资源而不是由 Web 应用程序处理时,应使用此方法。

getResource(java.lang.String path):getResource() 方法返回映射到指定路径的资源的 URL。当需要读取资源时应使用此方法,因为它将显示给客户端。

【讨论】:

  • 虽然如此,但这完全超出了实际问题和功能要求。 OP 正在尝试读取与他之前写入磁盘的几行代码非常相同的上传文件。
【解决方案2】:

您已经在file 中拥有该文件。直接替换

new FileReader(fileToBeRead)

通过

new FileReader(file)

或者,更好的是,完全跳过将文件写入磁盘的不必要步骤并立即读取上传的文件流。替换

File file = new File(destinationDir,item.getName());
item.write(file);
try {
    BufferedReader br = new BufferedReader(new FileReader(fileToBeRead));

通过

try {
    BufferedReader br = new BufferedReader(new InputStreamReader(item.getInputStream()));

您可能希望提供字符集作为第二个参数。我建议为此使用 UTF-8。

【讨论】:

  • 非常感谢。你的回答总是符合我的要求!
【解决方案3】:

您的代码已经包含解决方案:

getServletContext().getRealPath(DESTINATION_DIR_PATH);

这比:

String fileToBeRead = "C:/Program Files/Apache/Tomcat/...";

另外一点:永远不要使用new FileReader(),因为您无法指定用于将文件字节转换为所需字符的编码。请改用new InputStreamReader(is, encoding)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-15
    • 2015-07-16
    • 2013-09-18
    • 2018-10-29
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    • 2013-06-22
    相关资源
    最近更新 更多