`
liuyanttkl
  • 浏览: 19707 次
  • 性别: Icon_minigender_2
  • 来自: 上海
社区版块
存档分类
最新评论

小型WEB服务器程序解析2

阅读更多
接下来要实现的方法是把文件或者目录写到输出流中 发送给客户端,那么在方法里面的参数就可以定义为两个一个是客户端的请求参数(也就是客户端请求的URL) 一个是输出流:

Private void findFile(String url,OutputStream output) throws Exception

{

//用户提交的路径

String requestPath=url;

//?后面的请求字符串

String qeuryString="";


//用户提交的查询字符串,“?”前面的是路径 文件名,后面为请求参数


Int queryPos=url.indenxOf("?");

//如果?后面还有请求参数的时候

If(queryPos>0){

requestPath=url.subString(0,queryPos);

//queryPos+1是去掉“?”

qeuryString=url.subString(queryPos+1,url.length());

//打印出用户提交的路径和请求的字符串

System.out.println("requestPath:  "+requestPath);

System.out.println("qeuryString:  "+qeuryString);

//解析用户的查询参数

parseParameter(queryString);

System.out.println("paraMap:  "+paraMap.toString());


※:接下来 我们知道URL的分隔符跟文件系统的分隔符是不一样的 那么接下来做的就是怎么样来替换他们,那么接下来还要完成一个替换字符串的方法

requestPath=repalce(requestPath,"\","//").trim();

File tempFile=new File (requestPath) ;

If(tempFile.exists())

{

String parentPath=tempFile.getParent();

If(null!=parentPath)

{

String parentURL=repalce(requestPath,"//","\").trim();

parentURL="<p>返回上级: <a href=\"" + parentURL + "\">"+ parentPath + "</a></p><hr>";

output.getBytes(parentURL);


}

If(tempFile.isDirectory()){

//如果是目录 则列出目录下的文件

File[] f=tempFile.listsFile();

//如果目录下面没有文件

If(f.length==null)

{

outPut.write("<p>这个目录下没有文件</p>".getBytes());

return;


}


String html="";

For(int i=0;i<f.length;i++)

{

String fileName=f[i].getPath();

String urlPath=repalce(requestPath,"//","\").trim();

html += "<p><a href=\"" + urlPath + "\">" + f[i].getName()+"</a></p>";

}

System.out.println("request file is" + html);

outPut.write(html.getBytes());

try {

 output.write(html.getBytes());

 } catch (Exception e) {

  e.printStackTrace();

   }


}

}

//如果是文件 则直接读出

Else{

File file=new File(requestPath);

FileInputStream fis=null;

BUFFER_SIZE每一次读出的字符串流的大小

Byte[] bytes=new byte[BUFFER_SIZE]

fis = new FileInputStream(file);

If(file.exists())

{

int ch = fis.read(bytes, 0, BUFFER_SIZE);


}

while (ch != -1) {

      output.write(bytes, 0, ch);

      ch = fis.read(bytes, 0, BUFFER_SIZE);

     }


}

}

Else{

String errorMessage = "<html><h1>文件没有找到</h1></html>";

   output.write(errorMessage.getBytes());


}

}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics