Java,文件不存在错误即使它,Web服务器

时间:2015-01-11 21:00:43

标签: java

我正在编写一个基本的HTTP服务器,其中一个要求是服务器检查是否存在请求的文件。我的代码在下面

Scanner scn = new Scanner(lines[0]);
String command = scn.next();
String fileName = scn.next();

System.out.println("Command: " +command);
System.out.println("Resource: "+"www" +fileName);

File ifile = new File(fileName);
if( ! ifile.exists() ) {
System.out.println("file "+ fileName  + " doesn't exist");
} else {
String sizestr = "bytes in file: " + ifile.length();
System.out.println(sizestr);
}

我遇到的问题是我得到了文件不存在的响应,即使这样。有人可以帮忙吗?谢谢!

以下程序的完整代码:

import java.io.*;
import java.net.*;
import java.util.*;

public class UselessHTTPServer05 {
public static void main(String args[]) throws Exception {
int port = Integer.parseInt(args[0]);
ServerSocket serverSock=new ServerSocket(port);

while(true) {
  Socket conn = serverSock.accept();
  Scanner scanin = new Scanner(conn.getInputStream());
  String line=null;
  int nlines=0;
  String lines[] = new String[32];

  while (true) {
    line = scanin.nextLine();
if(line.length()==0) break;
lines[nlines] = line;
    nlines = nlines + 1;

  }


  for(int i=0; i<nlines; i=i+1) {
  System.out.println("line "+i+": "+lines[i]);
  }

  Scanner scn = new Scanner(lines[0]);
  String command = scn.next();
  String fileName = scn.next();

  System.out.println("Command: " +command);
  System.out.println("Resource: "+"www" +fileName);

   String webRoot = "/www";
   File f = new File(webRoot, fileName);
  if( ! f.exists() ) {
      System.out.println("file "+ f.getCanonicalPath() + " doesn't exist"); }
  else {
  String sizestr = "bytes in file: " + fileName;
  System.out.println(sizestr);
  }




  String reply="HTTP/1.0 404 Not Found\r\n" +
               "Connection: close\r\n" +
               "Content-Type: text/html\r\n" +
               "\r\n" +
               "<h1>Sorry, work in progress</h1>\r\n";


  OutputStream outs = conn.getOutputStream();
  outs.write(reply.getBytes());

  conn.close();
}
}
}

1 个答案:

答案 0 :(得分:1)

更改您的输出消息以包含一个电话File.getCanonicalPath(),这样您就可以确切地告诉他们在哪里读取内容;

System.out.println("file " + ifile.getCanonicalPath()  + " doesn't exist");

您可能应该使用File(String, String)构建File,这样您就可以设置&#34; webRoot&#34;第一,

String webRoot = "/some/directory"; 
File ifile = new File(webRoot, fileName);