发布
社区首页 >问答首页 >无法读取具有相对路径的文档文件

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

Stack Overflow用户
提问于 2014-07-29 02:59:56
回答 2查看 377关注 0票数 0

我已经从这个论坛上贴出的类似问题中寻找了解决方案,但无法摆脱这个问题。

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

但在托管期间,我尝试将其更改为相对路径(../docs/worfile.doc),并创建了一个WAR文件并托管。但这是行不通的。我在使用相对路径时感到困惑。

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

下面是我的代码:

代码语言:javascript
代码运行次数:0
复制
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;
    }   

}

而从其中读取文档文件触发器的jsp文件在WebContent中。

EN

回答 2

Stack Overflow用户

发布于 2014-07-29 03:55:36

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

因此,如果您运行的是像tomcat这样的服务器,那么相对路径可能是相对于用于启动服务器的.sh/.bat。

票数 0
EN

Stack Overflow用户

发布于 2014-07-29 03:11:11

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

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25002366

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档