java - 如何从绝对路径名创建文件对象?

标签 java file pathname

我认为我的问题需要对背景进行一些解释。我的任务是创建一个基本服务器,它将在我的系统上发送客户请求的 HTML 文件。我被告知只需在我的 firefox 浏览器中输入 localhost:8080/index.html 作为测试客户端来测试我的服务器。输入该行输入可以正常工作并打印出 index.html 的内容。为了安全起见,我应该进行测试以确保请求的文件在我当前的直接工作范围内,如果不是,我应该拒绝该请求。我已经设置了这样一个捕获,我想检查一下。我想再次使用我的文件 index.html,但要使用整个路径名 C:\Users\Gabrielle\Documents\NetBeansProjects\CS2 Assignment 5\src\index.html 所以我在浏览器中输入

localhost:8080/C:\Users\Gabrielle\Documents\NetBeansProjects\CS2 作业 5\src\index.html

我得到一个错误,说文件不存在。然后我检查它试图从中制作文件的内容以及它试图从中制作文件的内容,然后我得到了

C:%5CUsers%5C%5CGabreille%5C%5CDocuments%5C%5CNetBeansProjects%5C%5CCS2%20Assignment%205%5Cindex.html

这显然不是文件名。我只是错误地发送了文件名吗?如果它有什么不同,我正在从 Windows 命令提示符运行程序。下面是我的多线程客户端的代码和我的可运行对象的代码。如果您有任何疑问或想要了解一些信息,我会密切关注此话题。

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

public class WebServer {

    public static void main(String[] args)
    {
        try{
            ServerSocket ss = new ServerSocket(8080);
            while(true){
                Thread conn = new Thread(new ClientConnection(ss.accept()));
                conn.start();
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}

这里是实际内容

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

public class ClientConnection  implements Runnable{

private Socket socket;
File requestedFileName;
String entireInput ="";
String editedInput="";
String fileContent="";
String fileLine="";
PrintWriter out;
File defaultFile = new File("index.html");
File toBeRead;

public ClientConnection(Socket socket)
{
    this.socket=socket;
}

public void run()
{
    try{
        System.out.println("Client Connected");
        String workingDirectory = System.getProperty("user.dir");
        BufferedReader in =
                new BufferedReader(new InputStreamReader(socket.getInputStream()));
         out = new PrintWriter(socket.getOutputStream());
        String line;
            entireInput = in.readLine();

        editedInput= entireInput.substring(entireInput.indexOf("GET")+3,
                entireInput.indexOf("HTTP/1.1"));
        System.out.println("File name:" + editedInput);
        requestedFileName = new File(editedInput);
        System.out.println("What about here?");
        if(editedInput.equals(" / ") || editedInput.equals("  "))
        {
            toBeRead = defaultFile;
            System.out.println("Parent file "+toBeRead.getParent());
            String absolutePath = toBeRead.getAbsolutePath();
            System.out.println("absolute path "+ absolutePath);
            String filePath = absolutePath.substring(0,absolutePath.lastIndexOf(File.separator));
            if(filePath.equals(workingDirectory))
            {
                System.out.println("is in directory");
            }
            else{
                System.out.println("not in directory");
            }
        }
        else
        {   

            String hope = editedInput.substring(2);
            toBeRead = new File(hope);
        }

             //toBeRead = new File("index.html");
            if(toBeRead.exists())
            {
                System.out.println("File exists");
            }
            else
            {
                System.out.println("file doesn't exist");
            }
           BufferedReader fileIn = new BufferedReader(new FileReader(toBeRead));

           while((fileLine = fileIn.readLine()) != null)
             {
               //System.out.println("can i get in while loop?");
               fileContent = fileContent + fileLine;
                //System.out.println("File content: \n" + fileContent);
             }

           out.print("HTTP/1.1 200 OK\r\n");
           out.print("content-type: text/html\r\n\r\n");
           out.print(fileContent);
           out.flush();
           out.close();

        }
        catch(FileNotFoundException f)
        {
            System.out.println("File not found");
            out.print("HTTP/1.1 404 Not Found\r\n\r\n");
            out.flush();
            out.close();
        }
        catch(Exception e)
        {
            out.print("HTTP/1.1 500 Internal Server Error\r\n\r\n");
            out.flush();
            out.close();
        }

    }
}

最佳答案

您为文件提供了一个相对路径,并期望它能够神奇地找到该文件。相对路径是相对于 JVM 的启动位置进行解析的。如果你想要一个绝对路径,你需要做类似的事情:

new File("C:\\Users\\Gabrielle\\Documents\\NetBeansProjects\\CS2 Assignment 5\\src\\index.html");

因为请求是 URLEncoded,所以您没有从对您的应用程序的请求中得到它。

当然,更好的解决方案是将文件放在相对于您的应用程序的合理位置并相对引用它。

关于java - 如何从绝对路径名创建文件对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15694332/

相关文章:

perl - 在 Perl 中验证路径

Java 数字模式递归

java - 删除项目的 Maven 性质后无法删除目标目录

可以列出给定路径内的文件和文件夹的 Linux 内核模块

javascript - 基于 .pathname 运行函数

common-lisp - Common Lisp 中的路径名,包含通配符的文件名

java - HSQL 和 hibernate : unsupported internal operation: Session

java - 无法打印从txt文件读取的数组

c - 使用文件运行程序时出现问题

java - JAR 在其自己的安装目录中没有写入权限 (Windows 8)