我收集的几个资料,没实践过,希望对你能有帮助:一个完整的上传bean  
标题: 一个完整的上传bean 
提交时间: 2001年7月5日 
提交人: Sager  
作者: popeyelin  
程序/作者主页:   //Title: Cnjsp's Project 
//Version: 
//Copyright: Copyright (c) 1999 
//Author: Popeye 
//Company: Cnjsp 
//Description: It is for cnjsp package popeyelin; 
import java.io.*; 
import javax.servlet.ServletInputStream; 
import javax.servlet.http.HttpServletRequest; public class transfer_multi { 
public String[] sourcefile = new String[255];//源文件名 
public String objectpath = "c:/";//目标文件目录 
public String[] suffix = new String[255];//文件后缀名 
public String[] objectfilename = new String[255];//目标文件名 
public ServletInputStream sis = null;//输入流 
public String[] description = new String[255];//描述状态 
public long size = 100*1024;//限制大小 
private int count = 0;//已传输文件数目 
private byte[] b = new byte[4096];//字节流存放数组 
private boolean successful = true; public void setSourcefile(HttpServletRequest request) throws java.io.IOException{ 
sis = request.getInputStream(); 
int a = 0; 
int k = 0; 
String s = ""; 
while((a = sis.readLine(b,0,b.length)) != -1){ 
s = new String(b,0,a); 
if((k = s.indexOf("filename=")) != -1){ 
s = s.substring(k+10); 
k = s.indexOf("\""); 
s = s.substring(0,k); 
sourcefile[count] = s; 
k = s.lastIndexOf('.'); 
suffix[count] = s.substring(k+1); 
System.out.println(suffix[count]); 
if(canTransfer(count)) transferfile(count); 

if(!successful) break; 


public int getCount(){ 
return count; 

public String[] getSourcefile(){ 
return sourcefile; 
} public void setObjectpath(String objectpath){ 
this.objectpath = objectpath; 

public String getObjectpath(){ 
return objectpath; 

private boolean canTransfer(int i){ 
suffix[i] = suffix[i].toLowerCase(); 
//这个是我用来传图片的,各位可以把后缀名改掉或者不要这个条件 
if(sourcefile[i].equals("")||(!suffix[i].equals("gif")&&!suffix[i].equals("jpg")&&!suffix[i].equals("jpeg"))) {description[i]="ERR suffix is wrong";return false;} 
else return true; 

private void transferfile(int i){ 
String x = Long.toString(new java.util.Date().getTime()); 
try{ 
objectfilename[i] = x+"."+suffix[i]; 
FileOutputStream out = new FileOutputStream(objectpath+objectfilename[i]); 
int a = 0; 
int k = 0; 
long hastransfered = 0;//标示已经传输的字节数 
String s = ""; 
while((a = sis.readLine(b,0,b.length)) != -1){ 
s = new String(b,0,a); 
if((k = s.indexOf("Content-Type:")) != -1) break; 

sis.readLine(b,0,b.length); 
while((a = sis.readLine(b,0,b.length)) != -1){ 
s = new String(b,0,a); 
if((b[0]==45)&&(b[1]==45)&&(b[2]==45)&&(b[3]==45)&&(b[4]==45)) break; 
out.write(b,0,a); 
hastransfered+=a; 
if(hastransfered>=size){ 
description[count] = "ERR The file "+sourcefile[count]+" is too large to transfer. The whole process is interrupted."; 
successful = false; 
break; 


if(successful) description[count] = "Right The file "+sourcefile[count]+" has been transfered successfully."; 
++count; 
out.close(); 
if(!successful){ 
sis.close(); 
File tmp = new File(objectpath+objectfilename[count-1]); 
tmp.delete(); 


catch(IOException ioe){ 
description[i]=ioe.toString(); 
} } public transfer_multi(){ 
//可以在构建器里面构建服务器上传目录,也可以在javabean调用的时候自己构建 
setObjectpath("/home/www/jspvhost4/web/popeyelin/images/"); 


————————————————————————————————从数据库中读取并生成图片的Servlet  [关键字: Java & JSP  人气:73]  
网友对本文的评论共有0篇 [查看/发表评论]     [专业IT技术论坛]  
  
大体思路 
1)创建ServletOutputStream对象out,用于以字节流的方式输出图像 
2)查询数据库,用getBinaryStream方法返回InputStream对象in 
3)创建byte数组用作缓冲,将in读入buf[],再由out输出 
 
注:下面的例程中数据库连接用了ConnectionPool,以及参数的获得进行了预处理 
 
package net.seasky.music; 
 
import javax.servlet.*; 
import javax.servlet.http.*; 
import java.io.*; 
import java.util.*; 
import java.sql.*; 
import net.seasky.util.*; 
import net.seasky.database.DbConnectionManager; 
 
public class CoverServlet extends HttpServlet { 
 private static final String CONTENT_TYPE = "image/gif"; 
 public void init(ServletConfig config) throws ServletException { 
   super.init(config); 
 } 
 
 public void doGet(HttpServletRequest request, HttpServletResponse response 
) throws ServletException, IOException { 
   response.setContentType(CONTENT_TYPE); 
   int albumID; 
   ServletOutputStream out = response.getOutputStream(); 
   try { 
     albumID = ParamManager.getIntParameter(request,"albumID",0); 
   } 
   catch (Exception e) { 
     response.sendRedirect("../ErroePage.jsp"); 
     return; 
   } 
   try { 
     InputStream in=this.getCover(albumID); 
     int len; 
     byte buf[]=new byte[1024]; 
     while ((len=in.read(buf,0,1024))!=-1) { 
       out.write(buf,0,len); 
     } 
   } 
   catch (IOException ioe) { 
     ioe.printStackTrace() ; 
   } 
 } 
 
 private InputStream getCover(int albumID) { 
   InputStream in=null; 
   Connection cn = null; 
   PreparedStatement pst = null; 
   try { 
     cn=DbConnectionManager.getConnection(); 
     cn.setCatalog("music"); 
     pst=cn.prepareStatement("SELECT img FROM cover where ID =?"); 
     pst.setInt(1,albumID); 
     ResultSet rs=pst.executeQuery(); 
     rs.next() ; 
     in=rs.getBinaryStream("img"); 
   } 
   catch (SQLException sqle) { 
     System.err.println("Error in CoverServlet : getCover()-" + sqle); 
     sqle.printStackTrace() ; 
   } 
   finally { 
     try { 
       pst.close() ; cn.close() ; 
     } 
     catch (Exception e) { 
       e.printStackTrace(); 
     } 
   } 
   return in; 
 } 
 
 public void destroy() { 
 } 
} ——————————————————————————————如何在Web页上实现文件上传     关键字:java      人气值: 
529 文档分类:
Java 贴文时间
2001-5-15 16:44:13 得票数: 
35 给贴子投票 
投票   收藏者:wxyxl
 出处:    
  
  public class UploadServlet extends HttpServlet
{
  //default maximum allowable file size is 100k
  static final int MAX_SIZE = 102400;
  //instance variables to store root and success message
  String rootPath, successMessage;
  /**
   * init method is called when servlet is initialized.
   */
  public void init(ServletConfig config) throws ServletException
  {
    super.init(config);
    //get path in which to save file
    rootPath = config.getInitParameter("RootPath");
    if (rootPath == null)
    {
      rootPath = "/";
    }
    /*Get message to show when upload is complete. Used only if
      a success redirect page is not supplied.*/
    successMessage = config.getInitParameter("SuccessMessage");
    if (successMessage == null)
    {
      successMessage = "File upload complete!";
    }
  }
  /**
   * doPost reads the uploaded data from the request and writes
   * it to a file.
   */
  public void doPost(HttpServletRequest request,
    HttpServletResponse response)
  {
    ServletOutputStream out=null;
    DataInputStream in=null;
    FileOutputStream fileOut=null;
    try
    {
      /*set content type of response and get handle to output
        stream in case we are unable to redirect client*/
      response.setContentType("text/plain");
      out = response.getOutputStream();
    }
    catch (IOException e)
    {
      //print error message to standard out
      System.out.println("Error getting output stream.");
      System.out.println("Error description: " + e);
      return;
    }
    try
    {
      //get content type of client request
      String contentType = request.getContentType();
      //make sure content type is multipart/form-data
      if(contentType != null && contentType.indexOf(
        "multipart/form-data") != -1)
      {
        //open input stream from client to capture upload file
        in = new DataInputStream(request.getInputStream());
        //get length of content data
        int formDataLength = request.getContentLength();
        //allocate a byte array to store content data
        byte dataBytes[] = new byte[formDataLength];
        //read file into byte array
        int bytesRead = 0;
        int totalBytesRead = 0;
        int sizeCheck = 0;
        while (totalBytesRead < formDataLength)
        {
          //check for maximum file size violation
          sizeCheck = totalBytesRead + in.available();
          if (sizeCheck > MAX_SIZE)
          {
            out.println("Sorry, file is too large to upload.");
            return;
          }
          bytesRead = in.read(dataBytes, totalBytesRead,
            formDataLength);
          totalBytesRead += bytesRead;
        }
        //create string from byte array for easy manipulation
        String file = new String(dataBytes);
        //since byte array is stored in string, release memory
        dataBytes = null;
        /*get boundary value (boundary is a unique string that
          separates content data)*/
        int lastIndex = contentType.lastIndexOf("=");
        String boundary = contentType.substring(lastIndex+1,
          contentType.length());
        //get Directory web variable from request
        String directory="";
        if (file.indexOf("name=\"Directory\"") > 0)
        {
          directory = file.substring(
            file.indexOf("name=\"Directory\""));
          //remove carriage return
          directory = directory.substring(
            directory.indexOf("\n")+1);
          //remove carriage return
          directory = directory.substring(
            directory.indexOf("\n")+1);
          //get Directory
          directory = directory.substring(0,
            directory.indexOf("\n")-1);
          /*make sure user didn't select a directory higher in
            the directory tree*/
          if (directory.indexOf("..") > 0)
          {
            out.println("Security Error: You can't upload " +
              "to a directory higher in the directory tree.");
            return;
          }
        }
        //get SuccessPage web variable from request
        String successPage="";
        if (file.indexOf("name=\"SuccessPage\"") > 0)
        {
          successPage = file.substring(
            file.indexOf("name=\"SuccessPage\""));
          //remove carriage return
          successPage = successPage.substring(
            successPage.indexOf("\n")+1);
          //remove carriage return
          successPage = successPage.substring(
            successPage.indexOf("\n")+1);
          //get success page
          successPage = successPage.substring(0,
            successPage.indexOf("\n")-1);
        }
        //get OverWrite flag web variable from request
        String overWrite;
        if (file.indexOf("name=\"OverWrite\"") > 0)
        {
          overWrite = file.substring(
            file.indexOf("name=\"OverWrite\""));
          //remove carriage return
          overWrite = overWrite.substring(
            overWrite.indexOf("\n")+1);
          //remove carriage return
          overWrite = overWrite.substring(
            overWrite.indexOf("\n")+1);
          //get overwrite flag
          overWrite = overWrite.substring(0,
            overWrite.indexOf("\n")-1);
        }
        else
        {
          overWrite = "false";
        }
        //get OverWritePage web variable from request
        String overWritePage="";
        if (file.indexOf("name=\"OverWritePage\"") > 0)
        {
          overWritePage = file.substring(
            file.indexOf("name=\"OverWritePage\""));
          //remove carriage return
          overWritePage = overWritePage.substring(
            overWritePage.indexOf("\n")+1);
          //remove carriage return
          overWritePage = overWritePage.substring(
            overWritePage.indexOf("\n")+1);
          //get overwrite page
          overWritePage = overWritePage.substring(0,
            overWritePage.indexOf("\n")-1);
        }
        //get filename of upload file
        String saveFile = file.substring(
          file.indexOf("filename=\"")+10);
        saveFile = saveFile.substring(0,
          saveFile.indexOf("\n"));
        saveFile = saveFile.substring(
          saveFile.lastIndexOf("\\")+1,
          saveFile.indexOf("\""));
        /*remove boundary ers and other multipart/form-data
          tags from beginning of upload file section*/
        int pos; //position in upload file
        //find position of upload file section of request
        pos = file.indexOf("filename=\"");
        //find position of content-disposition line
        pos = file.indexOf("\n",pos)+1;
        //find position of content-type line
        pos = file.indexOf("\n",pos)+1;
        //find position of blank line
        pos = file.indexOf("\n",pos)+1;
        /*find the location of the next boundary er
          (ing the end of the upload file data)*/
        int boundaryLocation = file.indexOf(boundary,pos)-4;
        //upload file lies between pos and boundaryLocation
        file = file.substring(pos,boundaryLocation);
        //build the full path of the upload file
        String fileName = new String(rootPath + directory +
          saveFile);
        //create File object to check for existence of file
        File checkFile = new File(fileName);
        if (checkFile.exists())
        {
          /*file exists, if OverWrite flag is off, give
            message and abort*/
          if (!overWrite.toLowerCase().equals("true"))
          {
            if (overWritePage.equals(""))
            {
              /*OverWrite HTML page URL not received, respond
                with generic message*/
              out.println("Sorry, file already exists.");
            }
            else
            {
              //redirect client to OverWrite HTML page
              response.sendRedirect(overWritePage);
            }
            return;
          }
        }
        /*create File object to check for existence of
          Directory*/
        File fileDir = new File(rootPath + directory);
        if (!fileDir.exists())
        {
          //Directory doesn't exist, create it
          fileDir.mkdirs();
        }
        //instantiate file output stream
        fileOut = new FileOutputStream(fileName);
        //write the string to the file as a byte array
        fileOut.write(file.getBytes(),0,file.length());
        if (successPage.equals(""))
        {
          /*success HTML page URL not received, respond with
            generic success message*/
          out.println(successMessage);
          out.println("File written to: " + fileName);
        }
        else
        {
          //redirect client to success HTML page
          response.sendRedirect(successPage);
        }
      }
      else //request is not multipart/form-data
      {
        //send error message to client
        out.println("Request not multipart/form-data.");
      }
    }
    catch(Exception e)
    {
      try
      {
        //print error message to standard out
        System.out.println("Error in doPost: " + e);
        //send error message to client
        out.println("An unexpected error has occurred.");
        out.println("Error description: " + e);
      }
      catch (Exception f) {}
    }
    finally
    {
      try
      {
        fileOut.close(); //close file output stream
      }
      catch (Exception f) {}
      try
      {
        in.close(); //close input stream from client
      }
      catch (Exception f) {}
      try
      {
        out.close(); //close output stream to client
      }
      catch (Exception f) {}
    }
  }
}————————————————————————————————用Java实现断点续传(HTTP)     
 
 
   
内容: 
 
(一)断点续传的原理 
(二)Java实现断点续传的关键几点 
(三)断点续传内核的实现 
关于作者 
 
 
 
 
钟华 ([email protected])
2001 年 5 月(一)断点续传的原理 
其实断点续传的原理很简单,就是在Http的请求上和一般的下载有所不同而已。
打个比方,浏览器请求服务器上的一个文时,所发出的请求如下:
假设服务器域名为wwww.sjtu.edu.cn,文件名为down.zip。
GET /down.zip HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-
excel, application/msword, application/vnd.ms-powerpoint, */*
Accept-Language: zh-cn
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)
Connection: Keep-Alive
服务器收到请求后,按要求寻找请求的文件,提取文件的信息,然后返回给浏览器,返回信息如下:
200
Content-Length=106786028
Accept-Ranges=bytes
Date=Mon, 30 Apr 2001 12:56:11 GMT
ETag=W/"02ca57e173c11:95b"
Content-Type=application/octet-stream
Server=Microsoft-IIS/5.0
Last-Modified=Mon, 30 Apr 2001 12:56:11 GMT
所谓断点续传,也就是要从文件已经下载的地方开始继续下载。所以在客户端浏览器传给
Web服务器的时候要多加一条信息--从哪里开始。
下面是用自己编的一个"浏览器"来传递请求信息给Web服务器,要求从2000070字节开始。
GET /down.zip HTTP/1.0
User-Agent: NetFox
RANGE: bytes=2000070-
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
仔细看一下就会发现多了一行RANGE: bytes=2000070-
这一行的意思就是告诉服务器down.zip这个文件从2000070字节开始传,前面的字节不用传了。
服务器收到这个请求以后,返回的信息如下:
206
Content-Length=106786028
Content-Range=bytes 2000070-106786027/106786028
Date=Mon, 30 Apr 2001 12:55:20 GMT
ETag=W/"02ca57e173c11:95b"
Content-Type=application/octet-stream
Server=Microsoft-IIS/5.0
Last-Modified=Mon, 30 Apr 2001 12:55:20 GMT
和前面服务器返回的信息比较一下,就会发现增加了一行:
Content-Range=bytes 2000070-106786027/106786028
返回的代码也改为206了,而不再是200了。
知道了以上原理,就可以进行断点续传的编程了。
(二)Java实现断点续传的关键几点 
(1)用什么方法实现提交RANGE: bytes=2000070-。
当然用最原始的Socket是肯定能完成的,不过那样太费事了,其实Java的net包中提供了这种功能。代码如下:
URL url = new URL("http://www.sjtu.edu.cn/down.zip");
HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection
();
//设置User-Agent
httpConnection.setRequestProperty("User-Agent","NetFox");
//设置断点续传的开始位置
httpConnection.setRequestProperty("RANGE","bytes=2000070");
//获得输入流
InputStream input = httpConnection.getInputStream();
从输入流中取出的字节流就是down.zip文件从2000070开始的字节流。
大家看,其实断点续传用Java实现起来还是很简单的吧。
接下来要做的事就是怎么保存获得的流到文件中去了。
保存文件采用的方法。
我采用的是IO包中的RandAccessFile类。
操作相当简单,假设从2000070处开始保存文件,代码如下:
RandomAccess oSavedFile = new RandomAccessFile("down.zip","rw");
long nPos = 2000070;
//定位文件指针到nPos位置
oSavedFile.seek(nPos);
byte[] b = new byte[1024];
int nRead;
//从输入流中读入字节流,然后写到文件中
while((nRead=input.read(b,0,1024)) > 0)
{
oSavedFile.write(b,0,nRead);
}怎么样,也很简单吧。
接下来要做的就是整合成一个完整的程序了。包括一系列的线程控制等等。(三)断点续传内核的实现
主要用了6个类,包括一个测试类。
SiteFileFetch.java负责整个文件的抓取,控制内部线程(FileSplitterFetch类)。
FileSplitterFetch.java负责部分文件的抓取。
FileAccess.java负责文件的存储。
SiteInfoBean.java要抓取的文件的信息,如文件保存的目录,名字,抓取文件的URL等。
Utility.java工具类,放一些简单的方法。
TestMethod.java测试类。
下面是源程序: 
/*
**SiteFileFetch.java
*/
package NetFox;
import java.io.*;
import java.net.*;
public class SiteFileFetch extends Thread {
SiteInfoBean siteInfoBean = null; //文件信息Bean
long[] nStartPos; //开始位置
long[] nEndPos; //结束位置
FileSplitterFetch[] fileSplitterFetch; //子线程对象
long nFileLength; //文件长度
boolean bFirst = true; //是否第一次取文件
boolean bStop = false; //停止标志
File tmpFile; //文件下载的临时信息
DataOutputStream output; //输出到文件的输出流
public SiteFileFetch(SiteInfoBean bean) throws IOException
{
siteInfoBean = bean;
//tmpFile = File.createTempFile ("zhong","1111",new File(bean.getSFilePath()));
tmpFile = new File(bean.getSFilePath()+File.separator + bean.getSFileName()+".info");
if(tmpFile.exists ())
{
bFirst = false;
read_nPos();
}
else
{
nStartPos = new long[bean.getNSplitter()];
nEndPos = new long[bean.getNSplitter()];
}}
public void run()
{
//获得文件长度
//分割文件
//实例FileSplitterFetch
//启动FileSplitterFetch线程
//等待子线程返回
try{
if(bFirst)
{
nFileLength = getFileSize();
if(nFileLength == -1)
{
System.err.println("File Length is not known!");
}
else if(nFileLength == -2)
{
System.err.println("File is not access!");
}
else
{
for(int i=0;i<nStartPos.length;i++)
{
nStartPos[i] = (long)(i*(nFileLength/nStartPos.length));
}
for(int i=0;i<nEndPos.length-1;i++)
{
nEndPos[i] = nStartPos[i+1];
}
nEndPos[nEndPos.length-1] = nFileLength;
}
}
//启动子线程
fileSplitterFetch = new FileSplitterFetch[nStartPos.length];
for(int i=0;i<nStartPos.length;i++)
{
fileSplitterFetch[i] = new FileSplitterFetch(siteInfoBean.getSSiteURL(),
siteInfoBean.getSFilePath() + File.separator + siteInfoBean.getSFileName(),
nStartPos[i],nEndPos[i],i);
Utility.log("Thread " + i + " , nStartPos = " + nStartPos[i] + ", nEndPos = " + nEndPos[i]);
fileSplitterFetch[i].start();
}
// fileSplitterFetch[nPos.length-1] = new FileSplitterFetch(siteInfoBean.getSSiteURL(),
siteInfoBean.getSFilePath() + File.separator + siteInfoBean.getSFileName(),nPos[nPos.length-1],nFileLength,nPos.length-1);
// Utility.log("Thread " + (nPos.length-1) + " , nStartPos = " + nPos[nPos.length-1] + ",
nEndPos = " + nFileLength);
// fileSplitterFetch[nPos.length-1].start();
//等待子线程结束
//int count = 0;
//是否结束while循环
boolean breakWhile = false;
while(!bStop)
{
write_nPos();
Utility.sleep(500);
breakWhile = true;
for(int i=0;i<nStartPos.length;i++)
{
if(!fileSplitterFetch[i].bDownOver)
{
breakWhile = false;
break;
}
}
if(breakWhile)
break;
//count++;
//if(count>4)
// siteStop();
}
System.err.println("文件下载结束!");
}
catch(Exception e){e.printStackTrace ();}
}
//获得文件长度
public long getFileSize()
{
int nFileLength = -1;
try{
URL url = new URL(siteInfoBean.getSSiteURL());
HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection ();
httpConnection.setRequestProperty("User-Agent","NetFox");
int responseCode=httpConnection.getResponseCode();
if(responseCode>=400)
{
processErrorCode(responseCode);
return -2; //-2 represent access is error
}
String sHeader;
for(int i=1;;i++)
{
//DataInputStream in = new DataInputStream(httpConnection.getInputStream ());
//Utility.log(in.readLine());
sHeader=httpConnection.getHeaderFieldKey(i);
if(sHeader!=null)
{
if(sHeader.equals("Content-Length"))
{
nFileLength = Integer.parseInt(httpConnection.getHeaderField(sHeader));
break;
}
}
else
break;
}
}
catch(IOException e){e.printStackTrace ();}
catch(Exception e){e.printStackTrace ();}
Utility.log(nFileLength);
return nFileLength;
}
//保存下载信息(文件指针位置)
private void write_nPos()
{
try{
output = new DataOutputStream(new FileOutputStream(tmpFile));
output.writeInt(nStartPos.length);
for(int i=0;i<nStartPos.length;i++)
{
// output.writeLong(nPos[i]);
output.writeLong(fileSplitterFetch[i].nStartPos);
output.writeLong(fileSplitterFetch[i].nEndPos);
}
output.close();
}
catch(IOException e){e.printStackTrace ();}
catch(Exception e){e.printStackTrace ();}
}
//读取保存的下载信息(文件指针位置)
private void read_nPos()
{
try{
DataInputStream input = new DataInputStream(new FileInputStream(tmpFile));
int nCount = input.readInt();
nStartPos = new long[nCount];
nEndPos = new long[nCount];
for(int i=0;i<nStartPos.length;i++)
{
nStartPos[i] = input.readLong();
nEndPos[i] = input.readLong();
}
input.close();
}
catch(IOException e){e.printStackTrace ();}
catch(Exception e){e.printStackTrace ();}
}
private void processErrorCode(int nErrorCode)
{
System.err.println("Error Code : " + nErrorCode);
}
//停止文件下载
public void siteStop()
{
bStop = true;
for(int i=0;i<nStartPos.length;i++)
fileSplitterFetch[i].splitterStop();
}
}
/*
**FileSplitterFetch.java
*/
package NetFox;
import java.io.*;
import java.net.*;
public class FileSplitterFetch extends Thread {
String sURL; //File URL
long nStartPos; //File Snippet Start Position
long nEndPos; //File Snippet End Position
int nThreadID; //Thread's ID
boolean bDownOver = false; //Downing is over
boolean bStop = false; //Stop identical
FileAccessI fileAccessI = null; //File Access interface
public FileSplitterFetch(String sURL,String sName,long nStart,long nEnd,int id) throws IOException
{
this.sURL = sURL;
this.nStartPos = nStart;
this.nEndPos = nEnd;
nThreadID = id;
fileAccessI = new FileAccessI(sName,nStartPos);
}
public void run()
{
while(nStartPos < nEndPos && !bStop)
{
try{
URL url = new URL(sURL);
HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection ();
httpConnection.setRequestProperty("User-Agent","NetFox");
String sProperty = "bytes="+nStartPos+"-";
httpConnection.setRequestProperty("RANGE",sProperty);
Utility.log(sProperty);
InputStream input = httpConnection.getInputStream();
//logResponseHead(httpConnection);
byte[] b = new byte[1024];
int nRead;
while((nRead=input.read(b,0,1024)) > 0 && nStartPos < nEndPos && !bStop)
{
nStartPos += fileAccessI.write(b,0,nRead);
//if(nThreadID == 1)
// Utility.log("nStartPos = " + nStartPos + ", nEndPos = " + nEndPos);
}
Utility.log("Thread " + nThreadID + " is over!");
bDownOver = true;
//nPos = fileAccessI.write (b,0,nRead);
}
catch(Exception e){e.printStackTrace ();}
}
}
//打印回应的头信息
public void logResponseHead(HttpURLConnection con)
{
for(int i=1;;i++)
{
String header=con.getHeaderFieldKey(i);
if(header!=null)
//responseHeaders.put(header,httpConnection.getHeaderField(header));
Utility.log(header+" : "+con.getHeaderField(header));
else
break;
}
}
public void splitterStop()
{
bStop = true;
}
}
/*
**FileAccess.java
*/
package NetFox;
import java.io.*;
public class FileAccessI implements Serializable{
RandomAccessFile oSavedFile;
long nPos;
public FileAccessI() throws IOException
{
this("",0);
}
public FileAccessI(String sName,long nPos) throws IOException
{
oSavedFile = new RandomAccessFile(sName,"rw");
this.nPos = nPos;
oSavedFile.seek(nPos);
}
public synchronized int write(byte[] b,int nStart,int nLen)
{
int n = -1;
try{
oSavedFile.write(b,nStart,nLen);
n = nLen;
}
catch(IOException e)
{
e.printStackTrace ();
}
return n;
}
}
/*
**SiteInfoBean.java
*/
package NetFox;
public class SiteInfoBean {
private String sSiteURL; //Site's URL
private String sFilePath; //Saved File's Path
private String sFileName; //Saved File's Name
private int nSplitter; //Count of Splited Downloading File
public SiteInfoBean()
{
//default value of nSplitter is 5
this("","","",5);
}
public SiteInfoBean(String sURL,String sPath,String sName,int nSpiltter)
{
sSiteURL= sURL;
sFilePath = sPath;
sFileName = sName;
this.nSplitter = nSpiltter;
}
public String getSSiteURL()
{
return sSiteURL;
}
public void setSSiteURL(String value)
{
sSiteURL = value;
}
public String getSFilePath()
{
return sFilePath;
}
public void setSFilePath(String value)
{
sFilePath = value;
}
public String getSFileName()
{
return sFileName;
}
public void setSFileName(String value)
{
sFileName = value;
}
public int getNSplitter()
{
return nSplitter;
}
public void setNSplitter(int nCount)
{
nSplitter = nCount;
}
}
/*
**Utility.java
*/
package NetFox;
public class Utility {
public Utility()
{
}
public static void sleep(int nSecond)
{
try{
Thread.sleep(nSecond);
}
catch(Exception e)
{
e.printStackTrace ();
}
}
public static void log(String sMsg)
{
System.err.println(sMsg);
}
public static void log(int sMsg)
{
System.err.println(sMsg);
}
}
/*
**TestMethod.java
*/
package NetFox;
public class TestMethod {
public TestMethod()
{ ///xx/weblogic60b2_win.exe
try{
SiteInfoBean bean = new SiteInfoBean("http://localhost/xx/weblogic60b2_win.exe","L:\\temp","weblogic60b2_win.exe",5);
//SiteInfoBean bean = new SiteInfoBean("http://localhost:8080/down.zip","L:\\temp","weblogic60b2_win.exe",5);
SiteFileFetch fileFetch = new SiteFileFetch(bean);
fileFetch.start();
}
catch(Exception e){e.printStackTrace ();}
}
public static void main(String[] args)
{
new TestMethod();
}
}  
————————————————————————————————jsp文件操作之读取篇
2000-12-19  动网先锋  2000-11-28· coolknight·yesky    文件操作是网站编程的重要内容之一,asp关于文件操作讨论的已经很多了,让我们来看看jsp中是如何实现的。 
  这里用到了两个文件,一个jsp文件一个javabean文件,通过jsp中调用javabean可以轻松读取文本文件,注意请放置一个文本文件afile.txt到web根目录的test目录下,javabean文件编译后将class文件放到对应的class目录下(tomcat环境)。 
Read.jsp<html>
<head>
<title>读取一个文件</title>
</head>
<body bgcolor="#000000">
<%--调用javabean --%>
<jsp:useBean id="reader" class="DelimitedDataFile" scope="request">
<jsp:setProperty name="reader" property="path" value="/test/afile.txt" />
</jsp:useBean><h3>文件内容:</h3><p><% int count = 0; %> 
<% while (reader.nextRecord() != -1) { %>
<% count++; %> 
<b>第<% out.print(count); %>行:</b> 
<% out.print(reader.returnRecord()); %><br>    
<% } %> 
</p>
</body>
</html>
//DelimitedDataFile.java bean文件源代码
//导入java包
import java.io.*;
import java.util.StringTokenizer;public class DelimitedDataFile 
{private String currentRecord = null;
private BufferedReader file;
private String path;
private StringTokenizer token;
//创建文件对象
public DelimitedDataFile()
{
     file = new BufferedReader(new InputStreamReader(System.in),1);

public DelimitedDataFile(String filePath) throws FileNotFoundException
{
     
     path = filePath;
     file = new BufferedReader(new FileReader(path));

     //设置文件路径
     public void setPath(String filePath)
        {
            
            path = filePath;
try {
file = new BufferedReader(new
FileReader(path));
} catch (FileNotFoundException e) {
            System.out.println("file not found");
            }
    
        } 
//得到文件路径
     public String getPath() {
        return path;

//关闭文件
public void fileClose() throws IOException
{
     
     file.close();

//读取下一行记录,若没有则返回-1
public int nextRecord()
{
     
    
     int returnInt = -1;
     try
     {
     currentRecord = file.readLine();
     } 
    
     catch (IOException e)
     {
     System.out.println("readLine problem, terminating.");
     } 
    
     if (currentRecord == null)
     returnInt = -1;
     else
     {
     token = new StringTokenizer(currentRecord);
     returnInt = token.countTokens();
     } 
     return returnInt;
}     //以字符串的形式返回整个记录
public String returnRecord()
{return currentRecord;


      

解决方案 »

  1.   

    我是用servlet加jsp上传图片的,程序已经测试通过,并且用于一个日本的网站,如果你或者其他人想了解的话,请用QQ联系我,我的是2957946
      

  2.   

    可以用jspsmart这个上传组件做。 我是这么做的很好用的。
      

  3.   


    谢谢各位的帮助,我终于搞定了,用的是JSPSMART组件,呵呵!但我想上传在数据库中,请问lijunjoy 兄弟给我详细指点好吗? 有谢!
    相关连接也行!