<%//string?url?=?request.getrequesturi();string?">
 
网站首页
JSP空间
动态资讯
开源项目
技术文档
资源下载
J2EE资源
客户论坛
在线支付
 
  技术文档>>JAVA>>高级技术>>设计模式>查看文档  
  java对各种文件的操作详解     
  文章作者:未知  文章来源:中国IT实验室  
  查看:113次  录入:管理员--2007-11-20  
 

java中提供了io类库,可以轻松的用java实现对文件的各种操作。下面就来说一下如何用java来实现这些操作。
 
新建目录
<%@ page contenttype="text/html;charset=gb2312"%>
<%
//string url = request.getrequesturi();
string filepath="c:\\测试\\";
filepath=filepath.tostring();//中文转换
java.io.file myfilepath=new java.io.file(filepath);
if(!myfilepath.exists())
myfilepath.mkdir();
%>
 
新建文件
<%@ page contenttype="text/html;charset=gb2312"%>
<%@ page import="java.io.*" %>
<%
string filepath="c:/测试/newfile.txt";
filepath=filepath.tostring();
file myfilepath=new file(filepath);
if(!myfilepath.exists())
myfilepath.createnewfile();
filewriter resultfile=new filewriter(myfilepath);
printwriter myfile=new printwriter(resultfile);
string content ="这是测试数据";
string strcontent = content.tostring();
myfile.println(strcontent);
resultfile.close();
%>
 
删除文件
<%@ page contenttype="text/html;charset=gb2312"%>
<%
string filepath="c://测试//newfile.txt";
filepath=filepath.tostring();
java.io.file mydelfile=new java.io.file(filepath);
if(mydelfile.exists())
{  
    mydelfile.delete();
    out.println(filepath+"删除成功!!!");
}
else
{
    out.println(filepath+"该文件不存在");
}
%>
文件拷贝<%@ page contenttype="text/html; charset=gb2312" %>
<%@ page import="java.io.*" %>
<%
int bytesum=0;
int byteread=0;
//file:读到流中
inputstream instream=new fileinputstream("c://测试//newfile.txt");
fileoutputstream fs=new fileoutputstream( "c://测试//copyfile.txt");
byte[]  buffer =new  byte[1444];
int length;
while ((byteread=instream.read(buffer))!=-1)
 {
   out.println("<dt><b>"+byteread+"</b></dt>");
   bytesum+=byteread;
   out.println(bytesum);
   fs.write(buffer,0,byteread);
 }
instream.close();
%>
 
整个文件夹拷贝
<%@ page contenttype="text/html;charset=gb2312"%>
<%@ page import="java.io.*" %>
<%string url1="c:/aaa";
  string url2="d:/java/";
  (new file(url2)).mkdirs();
 file[] file=(new file(url1)).listfiles();
 for(int i=0;i<file.length;i++){
  if(file[i].isfile()){
   file[i].tostring();
   fileinputstream input=new fileinputstream(file[i]);
   fileoutputstream output=new fileoutputstream(url2+"/"+(file[i].getname()).tostring());
   byte[] b=new byte[1024*5];
    int len;
    while((len=input.read(b))!=-1){
    output.write(b,0,len);
    }
    output.flush();
    output.close();
    input.close();
  }
 }
%>
 

文件下载
<%@ page contenttype="text/html; charset=gb2312"%>
<%@ page import="java.io.*" %>
<%
  string filename = "newfile.txt".tostring();
  //读到流中
  inputstream instream=new fileinputstream("c://测试//newfile.txt");
  //设置输出的格式
  response.reset();
  response.setcontenttype("text/plain");
  response.addheader("content-disposition","attachment; filename="" + filename + """);
  //循环取出流中的数据
  byte[] b = new byte[100];
  int len;
  servletoutputstream outstream = response.getoutputstream();
 
  while((len=instream.read(b)) >0)
  outstream.write(b,0,len);
  outstream.flush();
  outstream.close();
  instream.close();
%>
 
数据库字段中的文件下载
<%@ page contenttype="text/html;charset=gb2312"%>
<%@ page import="java.util.*,java.sql.*,java.io.*"%>
<%
    string id = request.getparameter("id");
    if(id==null)
    {   throw new exception ("没有找到图片");
    }
    else
    {
       try
       {
com.gzrealmap.lib.jdbc.jdbcutil  sqlbean= com.gzrealmap.lib.jdbc.jdbcutil.getinstance();
               sqlbean.connect();
               string sql = "select * from innernews where id = '"+79+"'";
               resultset rs = sqlbean.queryforupdate(sql);
               rs.next();
               //string filenamedb = rs.getstring("imagename");
               string file= rs.getstring("acc");
               //string filename = new string(filenamedb.getbytes(),"iso-8859-1");
               string filename = "a.jpg";
                response.setheader("content-disposition",  "inline; filename=\"" + filename + "\"");    
               string filter = filename.substring(filename.lastindexof("."));
              
               if(filter.equals(".txt"))
               {
                   response.setcontenttype("text/plain");
               }
               else if(filter.equals(".doc")||filter.equals(".dot"))
               {
                   response.setcontenttype("application/msword");
               }
               else
               {
                 response.setcontenttype("image/jpeg;charset=gb2312");
               }
               servletoutputstream o = response.getoutputstream();
               //o.write(file);
               out.println(file);
               //o.flush();
               //o.close();
               sqlbean.disconnect();
       }
        catch(exception ex)
       {
           out.println(ex.getmessage());
       }
    }  
%>
 
把网页保存成文件
<%@ page contenttype="text/html;charset=gb2312"%>
<%@ page import="java.text.*,java.util.*,java.net.*,java.io.*"%>
<%
 url stdurl = null;
 bufferedreader stdin = null;
 printwriter stdout = null;
 try {
  stdurl = new url("http://www.163.com");
 }
 catch (malformedurlexception e) {
   throw e;
 }
 
try {
    //将字节流转变成为字符流
    stdin = new bufferedreader(new inputstreamreader(stdurl.openstream()));
    string thefilename = "c://测试//163.html";
    stdout = new printwriter(new bufferedwriter(new filewriter(thefilename.tostring())));
 }
 catch (ioexception e) {
 }
 
 /***把url指定的页面以流的形式读出,写成指定的文件***/
 try {
    string strhtml = "";
   while((strhtml = stdin.readline())!=null) {
   stdout.println(strhtml);
   }
 }
 catch (ioexception e) {
   throw e;
 }
 finally {  
   try {
     if(stdin != null)
       stdin.close();
     if(stdout != null)
       stdout.close();
       }
   catch (exception e) {
     system.out.println(e);
   }
 }
%>
 

直接下载网上的文件
<%@ page contenttype="text/html;charset=gb2312"%>
<%@ page import="java.io.*"%>
<%@ page import="java.net.*"%>
<%
  int bytesum=0;
  int byteread=0;
  url url = new url("/upfile/2007-11/20071120224952890.gif");
  byte[]  buffer =new  byte[1444];
    while ((byteread=instream.read(buffer))!=-1)
    {
       out.println("<dt><b>"+byteread+"</b></dt>");
       bytesum+=byteread;
       //system.out.println(bytesum);
       fs.write(buffer,0,byteread);
     }
%>
 
按行读文件 
<%@ page contenttype="text/html; charset=gb2312" %>
<%@ page import="java.io.*" %>
<%
filereader myfilereader=new filereader("c:/哈哈.txt");
bufferedreader mybufferedreader=new bufferedreader(myfilereader);
string mystring=null;
string resultstring=new string();
while((mystring=mybufferedreader.readline())!=null) {
resultstring=resultstring+mystring+"<br>";
}
out.println(resultstring);
myfilereader.close();
%>
 
对word文档的处理(上传与下载)
<%@ page contenttype="application/msword" %>
<!-- 以上这行设定本网页为excel格式的网页 -->
<%
   response.setheader("content-disposition","inline; filename=test1.doc"); //线上浏览方式
  // response.setheader("content-disposition","attachment; filename=test1.doc");//下载方式
   //以上这行设定传送到前端浏览器时的档名为test1.doc
   //就是靠这一行,让前端浏览器以为接收到一个word档
%>
//然后输出动态内容就可以得到一个word文档了
 
1,打开:
1)文件头上加:<%@ page  contenttype="application/msword"%> 
xml文件里:
<mime-mapping>
        <extension>doc</extension>
        <mime-type>application/msword</mime-type>
</mime-mapping>
2)可以用js,以下代码来自引用:
<%@ page contenttype="text/html;charset=gb2312" import= "java.io.*"%>
<html>
<script>
var wrd=new activexobject("word.application")
wrd.visible=true
alert ("您的"+wrd.application.caption+"安装路径为:\n"+wrd.application.path+"\n版本号是:"+ wrd.application.version+"\n注册使用者是:"+wrd.application.username)
wrd.documents.add()
//wrd.documents.open("c:\\exam.doc")
wrd.selection.typetext("this is some text.")
wrd.application.activate()
wrd.activedocument.saveas("c:\\exam111.doc")
wrd=null
</script>
</html>
 
2,下载:
<%@ page contenttype="text/html;charset=gb2312" import= "java.io.*"%>
<%// 得到文件名字和路径
  string filename = "jsp.doc";
  string filepath = "c:\\";
 
  // 设置响应头和下载保存的文件名
  response.setcontenttype("application/octet-stream");
  response.setheader("content-disposition","attachment; filename=\"" + filename + "\"");
 
  // 打开指定文件的流信息
  java.io.fileinputstream fileinputstream = new java.io.fileinputstream(filepath + filename);
  //fileoutputstream out  = new fileoutputstream(filepath+"测试\\" + filename);
  // 写出流信息
  int i;
  while ((i=fileinputstream.read()) != -1) {
   out.write(i);
  }
  fileinputstream.close();
  out.close();
 %> 

 
 
上一篇: java的多进程运行模式分析    下一篇: 单例模式singleton的实现
  相关文档
爪哇语言抽象工厂创立性模式介绍 03-14
java的多进程运行模式分析 11-20
composite模式及其在jsf中的应用 11-20
深入浅出java设计模式之备忘录模式 11-20
开发java编程中字符串分割的两种方法 11-20
虚拟代理模式(virtual proxy)(图) 11-20
Java模式设计之多态模式与多语言支持 03-14
爪哇语言工厂方法创立性模式介绍(下) 03-14
Java模式开发之责任链模式(上) 03-14
综合应用 j2ee应用中常见的反模式 11-20
追逐代码质量: 决心采用 fit 11-20
深入浅出基于java的建造设计模式 11-20
深入浅出java设计模式之迭代器模式(图) 11-20
外观设计模式组图(fa?ade pattern) 11-20
java设计模式之command(菜单命令) 11-20
java设计模式之template(算法的骨架) 11-20
大道至简java23种模式一点就通 11-16
戏说java设计模式中的命令模式 11-20
j2ee中几种业务代理模式的实现和比较 11-20
vrml与java在网络课件交互运用 11-20
返回首页 | 关于我们 | J网章程 | JSP空间合租 | 客服中心 | 免责声明 | 常见问题 | 参观机房
本站主机空间代理至厦门市华众网络科技有限公司
《中华人民共和国增值电信业务经营许可证》
编号:闽B2-20050079
@2005-2008福建JSP技术网 版权所有 闽ICP备05000928号
厦门(总部):13616026886 福州:0591-87655121
邮箱:admin@fjjsp.com 站长QQ,点击这里给我发消息