Chris V.
Chris V.

Reputation: 1143

Writing html file back to browser : Java

I've read a request for an HTML document from my browser, parsed the file from the request, found the specified file, and now all that's left is to send back the contents of the HTML file to the browser. What I'm currently doing seems like it should work just fine, however, the contents of the HTML file are not received by the browser.

public void sendResponse(File resource){
        System.out.println(resource.getAbsolutePath());

        Scanner fileReader;
        try {
            fileReader = new Scanner(resource);

            while(fileReader.hasNext()){
                socketWriter.println(fileReader.nextLine());
            }
        } catch (FileNotFoundException e) {
            System.out.println("File not found!");
            e.printStackTrace();
        }
    }

What am I doing incorrectly? There is no exception thrown, but the browser just keeps loading and loading.

Upvotes: 0

Views: 1285

Answers (3)

RHT
RHT

Reputation: 5054

It is not evident from your code, where socketWriter is going. Low level operations such as socket are best handled by the web server itself. Normally when we have to write a response back to the browser, we make use of HttpServletResponse object which is available in the goGet / doPost method of your servlet. Refer to the javadocs for more details.

Upvotes: 0

Ravi Bhatt
Ravi Bhatt

Reputation: 3163

that suggests your code is stuck in an infinite loop. Check your while loop. nextLine() is not moving the file pointer ahead?

Upvotes: 1

Samir Talwar
Samir Talwar

Reputation: 14330

It's hard to tell without knowing what type socketWriter is, but I imagine you'll need to close the connection. Look for a close() method or something similar on socketWriter and call it when you're done.

Upvotes: 0

Related Questions