在浏览器上打印多个空格时出现 java.io.PrintWriter 问题
我有一个文件,比如 test.txt。该文件包含一个名称列表作为内容。例如:示例内容为“Sachin Tendulkar”。请注意,名字和姓氏之间有四个空格。现在我有了 servlet,它的职责是读取文本文件并在浏览器上打印文件中的名称。我已经为其编写了以下 servlet 代码。
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();
}
}
浏览器上的结果: Sachin Tendulkar
请注意,在结果中,Sachin 和 Tendulkar 之间的剩余 3 个空格缺失。我需要所有四个空格。事实上,我们的项目中有报告功能,其中 servlet 读取如上所述的文本文件并在 Web 浏览器上打印。但是,只要文件中存在多个空格,打印人员就会删除多个空格并替换为单个空格。
请尝试上面的示例并为我提供有效的解决方案
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是
HTML
的一个功能,它会剪掉连续的空格,您需要在包含 DIV 下应用 css 属性white-space:pre;
以在视图上显示空格示例:
将在浏览器上生成类似于
A B
的输出现在让我们应用样式,
这将按照您的预期显示在浏览器上
It is a feature of
HTML
that will clip out the consecutive white spaces, You need to apply css attributewhite-space:pre;
under containing DIV to show spaces on viewfor example:
will generate output on browser looks like
A B
Now lets apply style
this will display on browser as you are expecting
使用不间断空格
代替空格。
Use a non-breaking space
instead of a space.