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

标签 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();
}
}
}

最佳答案

更改您的输出消息以包含调用 File.getCanonicalPath()这样你就可以准确地知道它试图从哪里读取;

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

您可能应该使用 File(String, String) 构建您的 File这样你就可以先设置一个“webRoot”,

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

关于Java,文件不存在错误,即使它存在,网络服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27892048/

相关文章:

java - 如何创建允许永久上传/更改个人资料图片的应用程序

java - Java中如何实现等价类?

java - JPA Criteria API - 设置连接并从连接实体中获取数据

java - 如何添加 JMenuBar 快捷方式?

java - Java 中的 String[] args 有什么意义?

java - 从 LDAP (Java) 检索信息

Java 程序运行良好但无法编译

java - 有没有人使用过 GWT 并且可以说它确实兑现了它的 promise ?

java - 我应该用一个字段创建 Spring 模型类吗?

java - 不同浏览器 session 中相同用户帐户的相同 JSF session ?