小型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());


}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值