关于文件浏览的自定义Web服务器

来源:互联网 发布:java和android的区别 编辑:程序博客网 时间:2024/06/05 14:55

刚开始看到这个题目的时候完全不理解这句话的意思,写过之后才慢慢知道了是啥意思,首先它是一个自己定义的web服务器,说明他是一个服务器其次是一个html,这样可以在java文件中写html标签。在详细一点就是说他是关于文件浏览的。

下面是关于写代码的思路和代码:

1、建立一个服务器,放在线程里运行

final ServerSocket ss = new ServerSocket(8080);new Thread() {public void run() {try {while (true) {Socket accept = ss.accept();
2、获取服务器的输入流得到报文头,存在char数组中

InputStream is = accept.getInputStream();InputStreamReader isr = new InputStreamReader(is);BufferedReader br = new BufferedReader(isr);char[] c = new char[1024];br.read(c);
3、将得到的报文头存在str数组中,再截取其中的路径(从get/到http),初始值为“”空的;要给一个默认的地址(E:);当截取的报文为空时,将E盘的地址赋给它,当不为空时,进行文件输出,要记得去除路径的空格,否则会出现找不到路径,用String的.trim()方法,例如:path=path.trim();如果遇到中文的文件夹,要解决乱码的问题,用URLDecode.decode(str,"UTF-8");的方法,是将str字符串转化为“UTF-8”的格式。



4、用服务器的输出流向网页上写数据,当是文件夹的时候写一个a标签,是文件的时候写一个p标签如:"<a href='"
+ "http://127.0.0.1:8080/" + herf+ "'>" + dirPath + "</a>" + "<br>");herf为默认的地址加上文件名,就可以获得文件夹下的下一级了。当遇到路径为"favicon.ico"时,为无效的路径,要进行处理if (path.equals("favicon.ico")) {continue;}



// 初始报文String str = new String(c);// 解决乱码str = URLDecoder.decode(str, "UTF-8");int old = str.indexOf("HTTP");// 截取空的String path = str.substring(5, old);// path = "E:\\UML";// 改变报文,赋初始值// String str2 = str.replace(http, "E:");// 截取改变后的报文的路径// String path = str2.substring(5, old);// System.out.println(str);System.out.println("++++++" + path);OutputStream os = accept.getOutputStream();OutputStreamWriter osw = new OutputStreamWriter(os);BufferedWriter bw = new BufferedWriter(osw);// path=null;将地址赋给pathif (" ".equals(path)) {path = "E:\\";System.out.println("path:" + path);}// System.out.println("path:" + path);// 去除前后空格path = path.trim();System.out.println("......" + path);// 无效的路径if (path.equals("favicon.ico")) {continue;}File file = new File(path);// 返回一个抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文件。File[] files = file.listFiles();for (int i = 0; i < files.length; i++) {// 是文件if (files[i].isFile()) {String filePath = files[i].getName();// 输出文件名bw.write("<p >" + filePath + "</p>" + "<br>");}// 是文件夹if (files[i].isDirectory()) {String dirPath = files[i].getName();// String herf = path + files[i].getName();// 输出链接,连接后的路径int count = 1;if (count % 2 != 0) {// path = path.trim();String herf2 = path + "//"+ files[i].getName();bw.write("<a href='"+ "http://127.0.0.1:8080/" + herf2+ "'>" + dirPath + "</a>" + "<br>");} else {// path = path.trim();String herf = path + files[i].getName();bw.write("<a href='"+ "http://127.0.0.1:8080/" + herf+ "'>" + dirPath + "</a>" + "<br>");count++;}


0 0
原创粉丝点击