Reading PDF file in Java - no external libraries

I've been writing a simple Java server for the past few weeks.

At first I wanted to display the filesystem based on where you started the server. For example, if you started a server in a directory src

, opened a browser, and went to localhost: 5555, you will see the files and directories contained in src

. Each of them will be linked. And it works fine for me.

If you click on a directory, it will show you its contents (as I mentioned). If you click a file, it reads the file and displays that file as plain text. When you click an image, it serves for that image. This all happens in the browser, and you can use the back button to return to the directory listing or file that you previously viewed. This also works great and does not use external libraries.

This is the code I am using to read a text file (with a reader):

private String readFile() {
    BufferedReader reader;
    String response = "";
    try {
        FileReader fileReader = new FileReader(requestedFile);
        reader = new BufferedReader(fileReader);
        String line;
        while ((line = reader.readLine()) != null) {
            response += line + "\n";
        }
        reader.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return response;
}

      

This is the code I am using to serve images (input stream instead of reader):

public byte[] getByteArray() throws IOException {
    byte[] byteArray = new byte[(int) requestedFile.length()];
    InputStream inputStream;
    String fileName = String.valueOf(requestedFile);
    inputStream = new BufferedInputStream(new FileInputStream(fileName));
    int bytesRead = 0;
    while (bytesRead < byteArray.length) {
        int bytesRemaining = byteArray.length - bytesRead;
        int read = inputStream.read(byteArray, bytesRead, bytesRemaining);
        if (read > 0) {
            bytesRead += read;
        }
    }
    inputStream.close();
    FilterOutputStream binaryOutputStream = new FilterOutputStream(outputStream);
    byte [] binaryHeaders = headers.getBytes();
    byte [] fullBinaryResponse = new byte[binaryHeaders.length + byteArray.length];
    System.arraycopy(binaryHeaders, 0, fullBinaryResponse, 0, binaryHeaders.length);
    System.arraycopy(byteArray, 0, fullBinaryResponse, binaryHeaders.length, byteArray.length);
    try {
        binaryOutputStream.write(fullBinaryResponse);
        binaryOutputStream.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

      

Now I am trying to use PDF files. If I have a PDF in one of the directories and I click it, it should open that PDF (in whatever default browser the browser uses).

I have searched this thread and tried several times for several days and I cannot get it. It's strange to me that when I click on PDF as my code currently, the browser seems to open the PDF, but no text appears. This is the browser's standard PDF viewer that we're all used to seeing when we click a PDF link. But there is no content. It's just a few blank pages.

Can anyone help with this? I will not use an external library. I just want to understand how to open a PDF file in Java.

Thank!

+3


source to share


1 answer


Don't parse it as text that converts characters, possibly ends lines, and might change what you don't like. Don't buffer the whole thing as a byte array, but instead write directly to the output stream to avoid memory issues. Instead, just execute the file like this:



public class FileServer extends javax.servlet.http.HttpServlet
{

public void doGet(HttpServletRequest req, HttpServletResponse resp)
{
    OutputStream out=null;
    try {

        HttpSession session = req.getSession();

        out = resp.getOutputStream();
        resp.setContentType(-- specify content type here --);
        req.setCharacterEncoding("UTF-8");

        String pathInfo = req.getPathInfo();

        String fullPath = -- figure out the path to the file in question --;

        FileInputStream fis = new FileInputStream(fullPath);

        byte[] buf = new byte[2048];

        int amtRead = fis.read(buf);
        while (amtRead > 0) {
            out.write(buf, 0, amtRead);
            amtRead = fis.read(buf);
        }
        fis.close();
        out.flush();
    }
    catch (Exception e) {
        try {
            resp.setContentType("text/html");
            if (out == null) {
                out = resp.getOutputStream();
            }
            Writer w = new OutputStreamWriter(out);
            w.write("<html><body><ul><li>Exception: ");
            w.write(e.toString());
            w.write("</ul></body></html>");
            w.flush();
        }
        catch (Exception eeeee) {
            //nothing we can do here...
        }
    }
}
}

      

+2


source







All Articles