无法读取具有相对路径的doc文件

时间:2014-07-28 18:59:56

标签: java servlets war relative-path

我已经在此论坛上发布的类似问题中搜索了解决方案,但无法解决此问题。

我正在使用Java和eclipse开发一个网站。我的网站读取一个doc文件并显示在其中一个页面上。因此,要在开发期间读取文件我使用绝对路径:(C:\\Documents and Settings\\Administrator\\Desktop\\wordfile.doc)并且它正常工作。

但是在主机上,这是在Linux服务器上,我试图将其更改为相对路径(../docs/worfile.doc)并创建一个WAR文件并托管。但这不起作用。我很困惑使用相对路径。

要读取doc文件的Java文件位于: Java Resources\src\com.ssoft.util\readdocfile.java

这是我的代码:

package com.ssoft.util;

import org.apache.poi.poifs.filesystem.*;
import org.apache.poi.hwpf.*;
import org.apache.poi.hwpf.extractor.*;

import java.io.*;
import java.net.URL;

public class readdocfile {

        /**This is the document that you want to read using Java.
         * @throws Exception **/
    public int totalparas() throws Exception{
        int totparas=0;
        POIFSFileSystem fs = null;
        String[] paragraphs=null;
        String fileName;

        fileName = "C:\\Documents and Settings\\Administrator\\Desktop\\wordfile.doc";


        try {

            fs = new POIFSFileSystem(new FileInputStream(fileName));
            HWPFDocument doc = new HWPFDocument(fs);

            /** Read the content **/
            WordExtractor we = new WordExtractor(doc);

            /**Get the total number of paragraphs**/
            paragraphs = we.getParagraphText();
            totparas=paragraphs.length;
            we.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return totparas;
    }   


    public String[] readDocument() throws Exception{
        POIFSFileSystem fs = null;
        String[] paragraphs=null;

        String fileName = "C:\\Documents and Settings\\Administrator\\Desktop\\wordfile.doc";
        try {
            fs = new POIFSFileSystem(new FileInputStream(fileName));
            HWPFDocument doc = new HWPFDocument(fs);

            /** Read the content **/
            WordExtractor we = new WordExtractor(doc);

            /**Get the total number of paragraphs**/
            paragraphs = we.getParagraphText();
            we.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return paragraphs;
    }   

}

读取doc文件触发器的jsp文件位于WebContent

2 个答案:

答案 0 :(得分:0)

java中具有相对路径的文件相对于启动java的目录进行解析。

因此,如果您正在运行像tomcat这样的服务器,则相对路径可能与您用于启动服务器的.sh / .bat相关。

答案 1 :(得分:-1)

在相对路径中查找错误的最简单方法是比较两个绝对路径。添加这些内容,如果仍有问题,我们可以提供更好的帮助。