Chinaunix首页 | 论坛 | 博客
  • 博客访问: 805297
  • 博文数量: 780
  • 博客积分: 7000
  • 博客等级: 少将
  • 技术积分: 5010
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-12 09:11
文章分类

全部博文(780)

文章存档

2011年(1)

2008年(779)

我的朋友
最近访客
[4]

分类:

2008-09-12 09:23:59

读入文件

    准备好 VXML 可供使用后,您也就为开始编码作好了最终的准备。首先从一个仅载入 VXML 文件的 Servlet 开始。清单 3 是一个实现此功能的 Servlet —— 载入 清单 2 中开发的 VXML。这段代码没有任何输出,所以期望值暂时不要太高。



				

package com.ibm.vxml;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;

public class VoiceXMLServlet extends HttpServlet {

  private static final String VXML_FILENAME =
    "simple-voice_recog.xml";

  public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {

    String vxmlDir = getServletContext().getInitParameter("vxml-dir");

    BufferedInputStream bis = null;
    ServletOutputStream out = null;

    try {
      // Load the VXML file
      File vxml = new File(vxmlDir + "/" + VXML_FILENAME);
      FileInputStream fis = new FileInputStream(vxml);
      bis = new BufferedInputStream(fis);

      // Output the VXML file 
      int readBytes = 0;
      while ((readBytes = bis.read()) != -1) {
        // output the VXML
      }
    } finally {
      if (out != null) out.close();
      if (bis != null) bis.close();
    }
  }
}


    这段代码非常直观。它载入一个 XML 文件 —— 通过 servlet 的配置上下文中的目录和一个常量文件名指定,然后遍历文件内容。您要将文件的路径硬编码到 servlet 中,但至少将目录名到 Web.xml 文件中是一个非常不错的主意,此文件位于 servlet 上下文的 WEB-INF/ 目录下。清单 4 展示了 Web.xml 中的上下文参数。



				
  
    vxml-dir
    /path-to-your-voicexml-dir/voicexml
  



    若编译 servlet 并尝试在 Web 浏览器中载入它,您只会看到一个空白的屏幕,同样,您应确保至少会看到这样的空白屏幕。如果得到错误,就需要予以更正。例如,常常会出现文件访问问题或 VXML 文件路径录入错误。一旦得到了空白屏幕,也就准备好实际输出 VXML 文件了。

首先,您需要访问一个输出对象,这样才能向浏览器发送内容。这非常简单:

      
// Load the VXML file
      File vxml = new File(vxmlDir + "/" + VXML_FILENAME);
      FileInputStream fis = new FileInputStream(vxml);
      bis = new BufferedInputStream(fis);

      // Let the browser know that XML is coming
      out = res.getOutputStream();
			

从文件提取内容也非常简单,只要使用一行代码即可:

      
// Output the VXML file 
      int readBytes = 0;
      while ((readBytes = bis.read()) != -1) {
        // output the VXML
        out.write(readBytes);
      }


    虽然上述代码看似已经足够,但您依然需要告知浏览器您正在向它发送 XML。切记,浏览器用于 HTML,某些浏览器可能无法顺利接收 XML。您可设置内容类型,也可设置内容的长度,只要再次使用 HttpServletResponse 对象即可:

     
 // Let the browser know that XML is coming
      out = res.getOutputStream();
      res.setContentType("text/xml");
      res.setContentLength((int)vxml.length());
			

 

     [4]      

【责编:Peng】

--------------------next---------------------

阅读(335) | 评论(0) | 转发(0) |
0

上一篇:比较comparable和Comparator

下一篇:[5]

给主人留下些什么吧!~~