在JAVA中生成输出 [英] Generating Output in JAVA

查看:93
本文介绍了在JAVA中生成输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以用java生成一个.html文件吗?通常我们会在运行java程序的cmd提示符下输出。我想以.html或.doc格式生成输出是他们在java中完成的一种方式吗?

解决方案

HTML只是简单的文本,带有一堆标签,正如其他人所回答的。我的建议是,如果你正在做的事情比输出一个基本的HTML片段更复杂,那就是使用模板引擎,比如 StringTemplate



使用StringTemplate可以创建一个如下所示的文本文件(实际上是一个HTML文件):

 < html> 
< head>
< title>示例< / title>
< / head>
< body>
< p> Hello $ name $< / p>
< / body>
< / html>

这是您的模板。然后在你的Java代码中,你可以像这样填写 $ name $ 占位符,然后输出结果HTML页面:

  StringTemplate page = group.getInstanceOf(page); 
page.setAttribute(name,World);
System.out.println(page.toString());

这会在屏幕上打印出以下结果:

 < html> 
< head>
< title>示例< / title>
< / head>
< body>
< p> Hello World< / p>
< / body>
< / html>

当然,上面的示例Java代码并不是完整的代码,但它说明了如何使用一个仍然有效的HTML模板(可以在HTML编辑器中编辑),同时保持Java代码的简单性(避免在 System.out.println 语句)。

至于MS Office .doc格式,则更为复杂,您可以查看 Apache POI


Can we generate an .html doc using java? Usually we get ouput in cmd prompt wen we run java programs. I want to generate output in the form of .html or .doc format is their a way to do it in java?

解决方案

HTML is simply plain text with a bunch of tags, as others have answered. My suggestion, if you are doing something that is more complex than just outputting a basic HTML snippet, is to use a template engine such as StringTemplate.

StringTemplate lets you create a text file (actually, a HTML file) that looks like this:

<html>
    <head>
       <title>Example</title>
    </head>
    <body>
       <p>Hello $name$</p>
   </body>
</html>

That is your template. Then in your Java code, you would fill in the $name$ placeholder like this and then output the resulting HTML page:

StringTemplate page = group.getInstanceOf("page");
page.setAttribute("name", "World");
System.out.println(page.toString());

This will print out the following result on your screen:

<html>
    <head>
       <title>Example</title>
    </head>
    <body>
       <p>Hello World</p>
   </body>
</html>

Of course, the above example Java code isn't the complete code, but it illustrates how to use a template that's still valid HTML (makes it easier to edit in a HTML editor) while keeping your Java code simple (by avoiding having a bunch of HTML tags in your System.out.println statements).

As for MS Office .doc format, that is more complex and you can look into Apache POI for that.

这篇关于在JAVA中生成输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆