简体   繁体   中英

Issue with java.io.PrintWriter while printing multiple spaces on the browser

I have a file, say test.txt. The file has a list of Names in it as content. Ex: Let the content be "Sachin Tendulkar" for sample. Observe that there are four spaces between the first name and last name . Now I have servlet, whose responsibility is to read the text file and print the name on the browser as it is exactly in the file. I have written the below servlet code for it.

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
    response.setContentType("text/html");

    try 
    {
        FileReader reader = new FileReader("E:/test.txt");
        BufferedReader bufferedReader = new BufferedReader(reader);
        PrintWriter pw = response.getWriter();

        String line = null;
        while( (line = bufferedReader.readLine()) !=null)
        {
            pw.write(line);
        }
        pw.close();


    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    }
}

Result on browser: Sachin Tendulkar

Note that in the result, the remaining 3 spaces between Sachin and Tendulkar is missing. I need all the four spaces. Infact we have report feature in our project where a servlet reads text file like above mentioned and prints on the web browser. But whenever there are more than one spaces in the file, the printwriter is removing multiple spaces and replacing with single space.

Please try the above sample and provide me a valid solution

It is a feature of HTML that will clip out the consecutive white spaces, You need to apply css attribute white-space:pre; under containing DIV to show spaces on view

for example:

<div>A    B</div>

will generate output on browser looks like AB

Now lets apply style

<div style="white-space:pre">A    B</div>

this will display on browser as you are expecting

Use a non-breaking space &nbsp; instead of a space.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM