Troubles arise with java.io.PrintWriter when attempting to print multiple spaces on the web browser

In the file named test.txt, I have a list of Names as content. For example, let's take "Sachin    Tendulkar" where there are four spaces between the first and last name. My servlet is responsible for reading this text file and displaying the names exactly as they appear in the file on the browser. Below is the servlet code I have written for this purpose.

    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 displayed on the browser: Sachin Tendulkar

However, the result does not show all 4 spaces between Sachin and Tendulkar. It appears that when there are multiple spaces in the file, the printwriter in the servlet condenses them into a single space. This is causing issues with our report feature that requires preserving all characters from the text file. Please help me find a solution to retain all spaces as shown in the sample above.

Answer №1

One interesting aspect of HTML is its ability to remove consecutive white spaces. To display these spaces on the browser, you can use the CSS attribute white-space:pre; within the containing DIV.

For instance:

<div>A    B</div>

will appear in the browser asA B

Now, let's add some style:

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

This will show in the browser exactly as you intend.

Answer №2

Opt for a non-breaking space with the code &nbsp; rather than using a regular space.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

VueJS - apply a rotation animation before showing the element

I'm having trouble displaying a line in different directions. While vertical and horizontal lines work fine, the diagonal direction requires rotation before it appears correctly. The issue is that it initially displays vertically before rotating to 13 ...

The use of event.returnValue is outdated and no longer supported. It is recommended to use the standard event.preventDefault() method instead. You may encounter

Hey there :) Currently, I am utilizing JQuery 1.9.1.js to search records using JSON. I am able to retrieve the search list locally, but when attempting to publish it on Windows Server 2008 and IIS 7, I face issues as it throws an error stating "event.ret ...

What is the best approach to decrease the size of a button in HTML and CSS when the text size is also reduced?

Check out this code snippet! I'm new to coding, so let me know if you see any errors or ways it could be improved. button { font-size: 10px; font-family: roboto, Arial; color: white; background-color: rgb(59, 102, 241); border-radius: 100p ...

Exploring the Features of TestNG and JUnit Frameworks within Selenium

My journey into learning Selenium began with YouTube videos and online tutorials. Now, I have a good grasp on topics like creating classes, interfaces, objects, inheritance, arrays, and loops in Java. When it comes to Selenium, I can automate tasks direc ...

Measuring the height of a div element using Vuejs

Let me explain my current situation: I am trying to determine the height of a DIV component in order to dynamically inform its child component about its size. I have been working on implementing manual loading mode, but I have encountered an issue where t ...

Can you provide a thorough explanation of how the 'for each' loop operates in Java?

Let's consider the following Java code snippet: List<String> someList = new ArrayList<>(); // add "monkey", "donkey", "skeleton key" to someList for (String item : someList) { System.out.println(item); } ...

Tips on how to choose a value from the Chrome autofill box that appears when filling out a form with Selenium

How can I retrieve the value from the Chrome autofill suggestion box that appears when filling out a form with Selenium? I attempted to use sendKeys(Keys.ARROWDOWN), but it was not successful. Can someone provide guidance on how I can accomplish this tas ...

Encountering syntax error with GLSL #version on Mac using LWJGL

Encountering a syntax error when specifying the GLSL version while using LWJGL on multiple Macs running Lion. I have not attempted to replicate this issue outside of LWJGL. Managed to make both vertex and fragment shaders function without using #version. ...

Is there a way to modify a document without altering its original location?

I attempted to load an entire page using ajax, with the doctype and html tags removed. However, when I tried setting it with the following code: document.documentElement.innerHTML=xmlhttp.responseText; Google Chrome returned an error message: An invalid ...

The application of border-radius causes the div to extend beyond its intended height

Is there a way to achieve a smooth shadow effect on pictures without it touching the corners? I attempted to do this by adding a border-radius and box-shadow to the parent div of the images, but now the parent div is taller than the picture itself. Any sug ...

Exploring the Potential of Boostrap 4 SCSS as a Mixin Toolbox

I discovered a helpful guide on using bootstrap at , but since v4 removed LESS, I'm struggling to achieve the same results with SCSS. It's quite useful and I can't seem to figure out the correct way to import it. ...

Nesting loops with combined th:field in Thymeleaf allows for a powerful and flexible way to

I'm currently developing a web app using Java/Spring/Thymeleaf and facing an issue when trying to display data from HashMaps in a list using th:field. Below are the classes I am working with: public class CompleteMeasurementResult { private L ...

After my jQuery functions are executed, my CSS rules are loaded

Struggling with the communication between CSS and jQuery, I find myself torn. In CSS, my rules are often very specific, like this: div#container > div#contentLeft { //Code here } However, when I add jQuery to spice up my site, the CSS rules seem to ...

Establish a connection to MongoDB using Morphia library in Java programming language

I have been attempting to establish a connection to MongoDb using Morphia in Java. After going through various tutorials and stackoverflow questions, I have noticed that they all use the deprecated method "createDatastore". Both of the alternative methods ...

What modifications were implemented in Bootstrap 5 to cause controls to automatically assume their maximum size?

After upgrading NodeJs to version 16.13.0 from 14.x, one of the modules that was updated was bootstrap. This caused me to remove my Jumbotron control due to the upgrade, although I don't believe that is directly related to the issue I am experiencing. ...

Issues with ASP.net rendering stylesheets

Here is the layout of my Index.cshtml page: <html> <head runat="server"> <link href="~/Content/index.css" rel="stylesheet" type="text/css" /> <asp:ContentPlaceHolder ID="HeadContent" runat="server" /> </head> < ...

Develop a pair of classes that inherit from Shape

You have been tasked with creating a graphical app that involves working with various shapes. The provided code introduces a base Shape class with an abstract area() method and a width attribute. Your objective is to develop two Shape subclasses, Square an ...

What methods can be used to effectively store text data in a file or multiple files for universal compatibility across different platforms?

Currently, I am in the process of creating a knowledge base java application that allows me to store and retrieve annotations along with their titles, creation dates (in SQL datetime format), content, tags, and more. While utilizing a database, such as SQ ...

Using ng-src and ngFor in Angular applications

Imagine taking photos based on an ID and storing them in an array like this: data.attributes.photos = [ "12.jpg", "12_1.jpg", "12_2.jpg" , 12_3.jpg, ... ] Then, using ngFor to display them: <ngb-carousel> <ng-template ngbSlide *ngFor="l ...

What is the reason behind the line-height adjustment only impacting the top portion of the font?

Currently, I am experimenting with the dot HTML character to create icons in different colors. However, I am encountering an issue with the line-height property. It appears that the line-height setting only affects the placement of the top part of the char ...