0

我有一个需要转换为 SharePoint 的 HTML 帮助系统。两个最耗时的项目是更改文档链接和收集元数据。但是,我很幸运,因为这些数据很容易访问。每个文件都是一个 HTML 文档,简化如下:

 <body>
   <!--- Metadata follows
   Procedure Name: my document
   Procedure Number: xxxxx
   Use: freeform text explaining when procdure is used
   Revision Date: xx/xx/xx
   By: responsible party for revision
   <!--- end metadata

   <h1>Procedure Name<\h1>
   <p>procedure background and narrative, with links, as needed, to other documents at \\documentation-server\path\document-name.html
 <\body>

我可以成功地提取和操作正确的字符串,并且我正在尝试将该过程合并到一个自动化解决方案中。然而,由于这是我第一次尝试文件 i/o,所以我对下一步该做什么有点模糊。

在一个完美的世界中,给定一个路径,我想逐步遍历路径中的每个 *.html 文件。我似乎找不到一个类/方法来做到这一点。newInputStreamnewOutpuStream给我文件访问权限,但我需要提供路径和文件参数。该FileVisitor界面似乎只与文件属性交互并执行删除/复制/重命名类型的功能。

有没有什么东西可以将这些组合成一个函数,该函数将逐步遍历路径中的每个文件,打开它并允许我逐行解析,然后关闭文件并移至下一个重复?

我的另一个想法是创建一个文件名数组,然后将该数组输入newInputStream.

建议?

4

4 回答 4

1

如果您使用 Java 7,FileVisitor 接口使您能够非常轻松地遍历文件树。例如,参见Java 教程

您可以覆盖该visitFile方法以对文件执行您想要的操作,例如(未测试):

@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {
    if (attr.isRegularFile() && file.getFileName().toString().endsWith(".html")) {
        Charset charset = Charset.forName("UTF-16");
        try (BufferedReader reader = Files.newBufferedReader(file, charset)) {
           String line;
           while ((line = reader.readLine()) != null) {
               System.out.println(line); //do what you need to do here
            }
         } catch (IOException x) {
             //Print / log the errror
         }
    }
    return CONTINUE;
}
于 2012-04-02T12:03:59.213 回答
1
java.io.File file = new File("yourPath");
if(file.isDirectory())
    for(File f : file.listFiles(new YourFileFilter()))
       doYourReading(new FileInputStream(f));

和:

class YourFileFilter extends java.io.FileFilter{
    public boolean accept(File pathname) {
          return pathname.getName().toLowerCase().endsWith(".html");
    }
}

这是基本的想法,至少。异常处理由您负责 (;

于 2012-04-02T12:04:36.577 回答
1

您需要 html 解析器 - http://htmlparser.sourceforge.net/。然后链接每个文档,它会做你想做的事。

于 2012-04-02T12:05:43.917 回答
1

这可能看起来有点违反直觉,但Filejava 中的对象也代表Directories

您可以通过执行以下操作检查它是否是目录:

file.isDirectory()

如果是,您可以列出所有文件并相应地处理它们:

for(File f : file.listFiles()){
   handle(f);
}
于 2012-04-02T12:07:48.423 回答