如何使用在Tomcat上运行的servlet来执行文件I / O [英] How to do file I/O with a servlet running on Tomcat

查看:118
本文介绍了如何使用在Tomcat上运行的servlet来执行文件I / O的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Java servlet,使用Tomcat作为容器,它创建并向最终用户提供PDF文件。目前PDF文件是在内存中创建的,并作为对POST的响应写出来。

I am writing a Java servlet, using Tomcat as the container, which creates and serves PDF files to the end-user. Currently the PDF files are created in-memory and written out as a response to a POST.

我想稍微改变一下,这样就可以将PDF文件写入磁盘(所以他们可以在以后再次服务)。我无法找到一个合适的如何做这样做。

I would like to change this up somewhat so that the PDF files are written to disk (so they can be served up again later). I am having trouble locating a suitable "how-to" for doing this.

如何配置我的servlet写入和从目录服务器读取文件从我读到的,我想我需要找到这个目录以外的地方,我的爆炸的webapp住在 $ CATALINA_BASE 出于安全原因,而且我需要使用 Context 或其他。

How can I configure my servlet to write to and read files from a directory server-side? From what I've read, I think I need to locate this directory somewhere outside where my "exploded webapp" lives in $CATALINA_BASE for security reasons, and I need to use a Context or somesuch.

推荐答案

可以使用通常的 FileOutputStream FileInputStream 类来分别写入和读取磁盘。改变你的PDF生成器,写入 FileOutputStream ,并将你的文件servlet改为从 FileInputStream

You can just use the usual FileOutputStream and FileInputStream classes to respectively write to and read from the disk. Change your PDF generator to write to FileOutputStream and change your file servlet to read from FileInputStream.

实际上,您希望将这些文件存储在webapp之外,否则每次重新部署webapp时都会丢失。您不需要 ServletContext ,它只对相对路径转换为绝对磁盘文件系统路径。当你将它存储在webapp之外时,你并不需要它,你已经知道了绝对的磁盘文件系统路径。

And, indeed, you'd like to store those files outside the webapp, else it will all get lost whenever you redeploy the webapp. You don't need the ServletContext, it's only useful to convert a relative web path to an absolute disk file system path. You don't need it when you're storing it outside the webapp, you namely already know the absolute disk file system path.

  • Java IO tutorial
  • Basic example of FileServlet

这篇关于如何使用在Tomcat上运行的servlet来执行文件I / O的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆