这个程序如何将输出的5个数字排列组合 排列在同一列上???

有一列数3 2 4 1 3 2 4 1排列前42个数的和是多少?
有一列数3 2 4 1 3 2 4 1排列前42个数的和是多少?
09-12-09 &匿名提问 发布
请登录后再发表评论!
3+2+4+1=1042/4=10......210*10+3+2=105前42个数的和是105.
请登录后再发表评论!
HTML指令详解结构<html><head><title>标题<title></head><body>..........文件内容..........</body></html>1.文件标题<title>..........</title>2.文件更新--<meta> 【1】10秒后自动更新一次  <meta http-equiv=&refresh& content=10> 【2】10秒後自动连结到另一文件  <meta http-equiv=&refresh& content=&10;URL=欲连结文件之URL&>3.查询用表单--<isindex&   若欲设定查询栏位前的提示文字:  <isindex prompt=&提示文字&>4.预设的基准路径--<base&   <base href=&放置文件的主机之URL&>版面1.标题文字 <h#>..........</h#> #=1~6;h1为最大字,h6为最小字2.字体变化 <font>..........</font> 【1】字体大小 <font size=#>..........</font> #=1~7;数字愈大字也愈大 【2】指定字型 <font face=&字型名称&>..........</font> 【3】文字颜色 <font color=#rrggbb>..........</font> rr:表红色(red)色码 gg:表绿色(green)色码 bb:表蓝色(blue)色码3.显示小字体 <small>..........</small> 4.显示大字体 <big>..........</big>5.粗体字 <b>..........</b>6.斜体字 <i>..........</i> 7.打字机字体 <tt>..........</tt>8.底线 <u>..........</u>9.删除线 <strike>..........</strike>10.下标字 <sub>..........</sub>11.上标字 <sup&..........</sup>12.文字闪烁效果 <blink>..........</blink>13.换行 <br>14.分段 <p> 15.文字的对齐方向 <p align=&#&> #号可为 left:表向左对齐(预设值) center:表向中对齐 right:表向右对齐 P.S.<p align=&#&>之後的文字都会以所设的对齐方式显示, 直到出现另一个<p align=&#&>改变其对齐方向,或遇到 <hr>ⅱ<h#>标签时会自动设回预设的向左对齐。16.分隔线 <hr> 【1】分隔线的粗细 <hr size=点数> 【2】分隔线的宽度 <hr size=点数或百分比> 【3】分隔线对齐方向 <hr align=&#&> #号可为 left:表向左对齐(预设值) center:表向中对齐 right:表向右对齐 【4】分隔线的颜色 <hr color=#rrggbb> 【5】实心分隔线 <hr noshade>17.向中对齐 <center>..........</center>18.依原始样式显示 <pre>..........</pre>19.<body>指令的属性 【1】背景颜色 -- bgcolor <body bgcolor=#rrggbb> 【2】背景图案 -- background <body background=&图形文件名&> 【3】设定背景图案不会卷动 -- bgproperties <body bgproperties=fixed> 【4】文件内容文字的颜色 -- text <body text=#rrggbb> 【5】超连结文字颜色 -- link <body link=#rrggbb> 【6】正被选取的超连结文字颜色 -- vlink <body vlink=#rrggbb> 【7】已连结过的超连结文字颜色 -- alink <body alink=#rrggbb>20.注解 <!--..........-->21.特殊字元表示法 符 号   语 法  <     &lt  >     &gt  &     &amp  &     &quot  空白    &nbsp    图片1.插入图片 <img src=&图形文件名&>2.设定图框 -- border <img src=&图形文件名& border=点数>3.设定图形大小 -- widthⅱheight <img src=&图形文件名& width=宽度点数 height=高度点数>4.设定图形上下左右留空 -- vspaceⅱhspace <img src=&图形文件名& vspace=上下留空点数 hspace=左右留空点数>5.图形附注 <img src=&图形文件名& alt=&说明文字&>6.预载图片<img src=&高解析度图形文件名& lowsrc=&低解析度图形文件名&> P.S.两个图的图形大小最好一致7.影像地图(Image Map) <img src=&图形文件名& usemap=&#图的名称&> <map name=&图的名称&>       <area shape=形状 coords=区域座标列表 href=&连结点之URL&>       <area shape=形状 coords=区域座标列表 href=&连结点之URL&>       <area shape=形状 coords=区域座标列表 href=&连结点之URL&>       <area shape=形状 coords=区域座标列表 href=&连结点之URL&>    </map>    【1】定义形状 -- shape       shape=rect:矩形         shape=circle:圆形         shape=poly:多边形    【2】定义区域 -- coordsa.矩形:必须使用四个数字,前两个数字为左上角座标,后两个数字为右下角座标例:<area shape=rect coords=100,50,200,75 href=&URL&>b.圆形:必须使用三个数字,前两个数字为圆心的座标,最后一个数字为半径长度例:<area shape=circle coords=85,155,30 href=&URL&>c.任意图形(多边形):将图形之每一转折点座标依序填入例:<area shape=poly coords=232,70,285,70,300,90,250,90,200,78 href=&URL&>表格1.定义表格 <table>..........</table> 【1】设定边框的厚度 -- border<table border=点数> 【2】设定格线的宽度 -- cellspacing<table cellspacing=点数> 【3】设定资料与格线的距离 -- cellpadding<table cellpadding=点数> 【4】调整表格宽度 -- width<table width=点数或百分比> 【5】调整表格高度 -- height<table height=点数或百分比> 【6】设定表格背景色彩 -- bgcolor<table bgcolor=#rrggbb> 【7】设定表格边框色彩 -- bordercolor<table bordercolor=#rrggbb>2.显示格线 <table border>3.表格标题<caption>..........</caption> 表格标题位置 -- align<caption align=&#&> #号可为 top:表标题置于表格上方(预设值)bottom:表标题置于表格下方4.定义列 <tr>5.定义栏位 《1》<td>:靠左对齐《2》<th>:靠中对齐ⅱ粗体 【1】水平位置 -- align <th align=&#&>#号可为 left:向左对齐center:向中对齐 right:向右对齐【2】垂直位置 -- align <th align=&#&> #号可为top:向上对齐 middle:向中对齐bottom:向下对齐 【3】栏位宽度 -- width<th width=点数或百分比> 【4】栏位垂直合并 -- rowspan<th rowspan=欲合并栏位数> 【5】栏位横向合并 -- colspan<th colspan=欲合并栏位数>清单一、目录式清单 <dir> <li>项目1 <li>项目2 <li>项目3 </dir> P.S.目录式清单每一个项目不能超过20个字元(即10个中文字)二、选项式清单 <menu> <li>项目1 <li>项目2 <li>项目3 </menu>三、有序号的清单 <ol> <li>项目1 <li>项目2 <li>项目3 </ol> 【1】序号形式 -- type <ol type=#>或<li type=#> #号可为 A:表以大写英文字母AⅱBⅱCⅱD...做为项目编号 a:表以小写英文字母aⅱbⅱcⅱd...做为项目编号 I:表以大写罗马数字做为项目编号 i:表以小写罗马数字做为项目编号 1:表以阿拉伯数字做为项目编号(预设值) 【2】起始数字 -- start <ol start=欲开始计数的序数> 【3】指定编号 -- value <li value=欲指定的序数>四、无序号的清单 <ul> <li>项目1 <li>项目2 <li>项目3 </ul> 【1】项目符号形式 -- type <ul type=#>或<li type=#> #号可为 disc:实心圆点(预设值) circle:空心圆点 square:实心方块 【2】原始清单 -- plain <ul plain> 【3】清单排列方式 -- warp 《1》清单垂直排列 <ul warp = vert> 《2》清单水平排列 <ul warp = horiz>五、定义式清单 <dl> <dt>项目1 <dd>项目1说明 <dt>项目2 <dd>项目2说明 <dt>项目3 <dd>项目3说明 </dl> 紧密排列 -- compact <dl compact> P.S.如此可使<dt>的内容与<dd>的内容在同一行,仅 以数格空白相隔而不换行,但若<dt>的文字超过一 定的长度后,compact的作用就消失了!表单一、基本架构 <form action=&处理资料用的CGI程式之URL&或&mailto:电子信箱的URL& method=&get或post&> .......... .......... .......... </form> 二、输入文件型表单 <form action=&URL& method=&post&> <input> <input> .......... .......... </form> 【1】栏位类型 -- type <input type=#> #号可为 text:文字输入 password:密码 checkbox:多选钮 radio:单选钮 submit:接受按钮 reset:重设按钮 image:图形钮 hidden:隐藏栏位 【2】栏位名称 -- name <input name=&资料栏名&> P.S.若type为submitⅱreset则name不必设定 【3】文件上的预设值 -- value <input value=&预设之字串&> 【4】设定栏位的宽度 -- size <input size=字元数> 【5】限制最大输入字串的长度 -- maxlength <input maxlength=字元数> 【6】预设checkbox或radio的初值 -- checked <input type=checkbox checked> <input type=radio checked> 【7】指定图形的URL -- src <input type=image src=&图档名&> 【8】图文对齐 -- align <input type=image align=&#&> #号可为 top:文字对齐图片之顶端 middle:文字对齐图片之中间 buttom:文字对齐图片之底部三、选择式表单 <form action=&URL& method=&post&> <select> <option> <option> .......... .......... </select> </form> A、<select>的属性 【1】栏位名称 -- name <select name=&资料栏位名&> 【2】设定显示的选项数 -- size <select size=个数> 【3】多重选项 -- multiple <select multiple> B、<option>的属性 【1】定义选项的传回值 -- value <option value=&传回值&> 【2】预先选取的选项 -- selected <option selected>四、多列输入文字区表单 <form action=&URL& method=&post&> <textarea> .......... .......... </textarea> </form> 【1】文字区的变数名称 -- name <textarea name=变数名称> 【2】设定文字输入区宽度 -- cols <textarea cols=字元数> 【3】设定文字输入区高度 -- rows <textarea rows=列数> 【4】输入区设定预设字串 <textarea> 预设文字 </textarea> 【5】自动换行与否 -- wrap <textarea wrap=#> #号可为 off:表输入的文字超过栏宽时,不会自动换行(预设值) virtual:表输入的文字在超过栏宽时会自动换行链接一、连结至其他文件 <a href=&URL&>说明文字或图片</a>二、连结至文件内之某一处(外部连结) 《1》起点<a href=&档名#名称&>..........</a> 《2》终点 <a name=&名称&>三、frame的超连结 【1】开启新的浏览器来显示连结文件 -- _blank <a href=&URL& target=_blank>【2】显示连结文件於目前的frame -- _self <a href=&URL& target=_self>【3】以上一层的分割视窗显示连结文件 -- _parent <a href=&URL& target=_parent>【4】以全视窗显示连结文件 -- _top <a href=&URL& target=_top> 【5】以特定视窗显示连结文件 --<a href=&URL& target=&特定视窗名称&>FRAME一、分割视窗指令 <frameset>..........</frameset> 【1】垂直(上下)分割 -- rows<frameset rows=#> #号可为点数:如欲分割为100,200,300三个视窗,则<frameset rows=100,200,300>;亦可以*号代表,如<frameset rows=*,500,*>百分比:如<frameset rows=30%,70%>,各 项总和最好为100%【2】水平(左右)分割 -- cols <frameset cols=点数或百分比>二ⅱ指定视窗内容 -- <frame><frameset cols=30%,70%>    <frame>    <frame> </frameset>【1】指定视窗的文件名称 -- src <frame src=HTML档名> 【2】定义视窗的名称 -- name<frame name=视窗名称> 【3】设定文件与上下边框的距离 -- marginheight<frame marginheight=点数> 【4】设定文件与左右边框的距离 -- marginwidth<frame marginwidth=点数> 【5】设定分割视窗卷轴 -- scrolling<frame scrolling=#> #号可为 yes:固定出现卷轴no:不出现卷轴 auto:自动判断文件大小需不需要卷轴(预设值)【6】锁住分割视窗的大小 -- noresize <frame noresize>
请登录后再发表评论!1、有这样一个Room类:
public class Room {
&* 房间名称
private String roomN
&* 房间面积
&* 房间价格
private BigD
&* 酒店的地址
&* 酒店的电话
private String phoneNumber
还有这样一个Person类:
public class Person {
现在我们需要用HashMap做一个以room为key,以person为value的缓存,以提供快速查询指定房间入住了哪些人?
请完成一个可以运行的演示。
public class Person {
public Person(String name, int age, int weight){
this.username =
this.age =
this.weight =
public boolean equals(Object obj) {
if(!(obj instanceof Person))
Person p = (Person)
return this.username.equals(p.username)&&
this.age == p.age&&
this.weight == p.
public class Room {
private String roomN
private BigD
private String phoneN
public Room(String roomName, int area, BigDecimal price, String address, String phoneNumber){
this.roomName = roomN
this.area =
this.price =
this.address =
this.phoneNumber = phoneN
public int hashCode(){
int result = roomName.hashCode();
result = 31*result +
result = 31*result + address.hashCode();
result = 31*result + phoneNumber.hashCode();
return Objects.hashCode(roomName, area, address, phoneNumber);
public boolean equals(Object obj) {
if(!(obj instanceof Room))
Room tmpRoom = (Room)
return this.address.equals(tmpRoom.address)&&
this.phoneNumber.equals(tmpRoom.phoneNumber)&&
this.roomName.equals(tmpRoom.roomName)&&
this.area==tmpRoom.
public class RoomCache {
HashMap&Room, Person&
public RoomCache(){
cache = new HashMap&Room, Person&();
public void put(Room room, Person person){
cache.put(room, person);
public Person get(Room room){
return cache.get(room);
2、根据指定项目目录下(可以认为是java源文件目录)中,统计被import最多的类。
public class MostImportClass {
String dirN
HashMap&String, Integer& importClassR
public MostImportClass(String dir){
this.dirName =
importClassRecords = new HashMap&String, Integer&();
this.statisticsClazz(new File(this.dirName));
public int get(String clazzName){
Integer value = importClassRecords.get(clazzName);
if(value==null) return 0;
public void processFile(File file){
reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
String line =
while((line = reader.readLine()) != null){
line = line.trim();
if(line.startsWith(&public&)||line.startsWith(&class&)){
if(line.startsWith(&import&)){
String className = line.substring(6, line.length()-1).trim();
Integer value = importClassRecords.get(className);
if(value==null){
importClassRecords.put(className, 1);
importClassRecords.put(className, value+1);
} catch (IOException e) {
e.printStackTrace();
public void statisticsClazz(File file){
if(!file.isDirectory()){
processFile(file);
File [] files = file.listFiles();
for(File tmpFile: files){
statisticsClazz(tmpFile);
public String getMostImportClazzName(){
int max = Integer.MIN_VALUE;
String clazzName =
for(Entry item: this.importClassRecords.entrySet()){
String key = (String) item.getKey();
int value = (Integer)item.getValue();
if(value&max){
clazzName =
return clazzN
1) 查找一个目录下,所有文件中数字、字母(大小写不区分)、汉字、空格的个数、行数。
2) 将结果数据写入到文件中。
文件格式如下:
数字:198213个
字母:18231个
汉字:1238123个
空格:823145个
行数:99812行
数字0:123个
数字1:1214个
数字2:23423个
字母A:754456个
数字B:7567个
数字C:456456个
class Item{
public Item(int x){
public String toString(){
return this.x+&&;
* @author Cool
*/public class GuavaTest implements Comparable&GuavaTest&{
public GuavaTest(int x, int y){
public String toString(){
String ss = MoreObjects.toStringHelper(&GuavaTest&)
.add(&x&, 12)
.add(&b&, false)
.toString();
public int compareTo(GuavaTest o) {
return ComparisonChain.start()
.compare(this.x, o.x)
.compare(this.y, o.y)
.result();
public static void countChinese(){
String str = new String(&abc中国cd你好啊89&);
String E1 = &[\u4e00-\u9fa5]&;// 中文
String E2 = &[a-zA-Z]&;// 英文
String E3 = &[0-9]&;// 数字
int chineseCount = 0;
int englishCount = 0;
int numberCount = 0;
System.out.println(&length = &+str.length());
System.out.println(&bytes length = &+str.getBytes().length);
for (int i = 0; i & str.length(); i++)
temp = String.valueOf(str.charAt(i));
if (temp.matches(E1))
chineseCount++;
if (temp.matches(E2))
englishCount++;
if (temp.matches(E3))
numberCount++;
System.out.println(&汉字数:& + chineseCount);
System.out.println(&英文数:& + englishCount);
System.out.println(&数字数:& + numberCount);
System.out.println(&特殊字符:& + (str.length() - (chineseCount + englishCount + numberCount)));
public static void countFile(String filename) throws IOException{
File file = new File(filename);
List&String& lines = Files.readLines(file, Charsets.UTF_8);
String E1 = &[\u4e00-\u9fa5]&;// 中文
String E2 = &[a-zA-Z]&;// 英文
String E3 = &[0-9]&;// 数字
String E4 = & &;
int chineseCount = 0;
int englishCount = 0;
int numberCount = 0;
int spaceCount = 0;
int lineCount = 0;
TreeMultiset&String& chineseWordsCount = TreeMultiset.create(),
englishWordsCount = TreeMultiset.create(),
numberWordsCount = TreeMultiset.create();
for(String line : lines){
lineCount ++;
line = line.toLowerCase();
for(int i=0; i&line.length(); i++){
String word = String.valueOf(line.charAt(i));
if(word.matches(E1)){
chineseCount++;
chineseWordsCount.add(word);
}else if(word.matches(E2)){
englishCount++;
englishWordsCount.add(word);
}else if(word.matches(E3)){
numberCount++;
numberWordsCount.add(word);
}else if(word.matches(E4)){
spaceCount++;
System.out.println(&数字:&+numberCount+&个&);
System.out.println(&字母:&+englishCount+&个&);
System.out.println(&汉字:&+chineseCount+&个&);
System.out.println(&空格:&+spaceCount+&个&);
System.out.println(&行数:&+lineCount+&行\n&);
for(String word: numberWordsCount.elementSet()){
System.out.println(&数字&+word+&:&+numberWordsCount.count(word)+&个&);
for(String word: englishWordsCount.elementSet()){
System.out.println(&字母&+word+&:&+englishWordsCount.count(word)+&个&);
for(String word: chineseWordsCount.elementSet()){
System.out.println(&汉字&+word+&:&+chineseWordsCount.count(word)+&个&);
public static void countCodeLines(String filename) throws IOException{
int linesCount = 0;
File file = new File(filename);
List&String& lines = Files.readLines(file, Charsets.UTF_8);
boolean incomment =
String tab = &\\s+&;
for(String line : lines){
line = line.trim();
if(line.startsWith(&//&)||line.equals(&&))
if(!incomment&&!line.startsWith(&/*&)){
linesCount ++ ;
if(line.contains(&/*&)){
incomment =
if(incomment&&line.contains(&*/&)){
incomment =
line = line.substring(line.indexOf(&*/&)+2).trim();
if(line!=&&&&!line.startsWith(&//&)){
linesCount ++;
System.out.println(linesCount);
public static void main(String [] args) throws IOException{
countFile(&./src/main/java/MyTest/MyTest/myguava/GuavaTest.java&);
countCodeLines(&./src/main/java/MyTest/MyTest/myguava/TestClass.java&);
int count = 0;
System.out.println(!true&&(count++ == 0));
String line = &8&;
System.out.println(line.substring(8));
String s =/**
Optional&String& possible = Optional.fromNullable(s);
System.out.println(possible.isPresent());
Preconditions.checkNotNull(s, &s is null&);
System.out.println(new GuavaTest(1, 1));
GuavaTest g = new GuavaTest(1, 1), g2 = new GuavaTest(1, 2);
System.out.pareTo(g2));
Ordering&Item& order = Ordering.natural().onResultOf(new Function&Item, Integer&(){
public Integer apply(Item input) {
return input.x;
List&Item& list = new ArrayList&Item&();
list.add(new Item(9));
list.add(new Item(2));
list.add(new Item(10));
List&Item& tmp = order.sortedCopy(list);
System.out.println(tmp);
ImmutableSet&String& set = ImmutableSet.of(&a&, &b&, &c&);
for(String s: set){
System.out.println(&+&+s);
Multiset&String& mset = HashMultiset.create();
mset.add(&a&);
mset.add(&b&);
mset.add(&c&);
mset.add(&a&);
for(String s: mset){
System.out.println(&+&+s);
System.out.println(mset.count(&a&));
BiMap&String, Integer& userId = HashBiMap.create();
userId.put(&a&, 1);
userId.put(&a&, 2);
userId.put(&b&, 3);
System.out.println(userId.get(&a&));
System.out.println(userId.inverse().get(1));
4、统计附件中的StringUtils.java文件的有效代码行数。&
1) 有效不包括空行、注释
2) 考虑代码里有多行注释的情况
class Item{
public Item(int x){
public String toString(){
return this.x+&&;
* @author Cool
*/public class GuavaTest implements Comparable&GuavaTest&{
public GuavaTest(int x, int y){
public String toString(){
String ss = MoreObjects.toStringHelper(&GuavaTest&)
.add(&x&, 12)
.add(&b&, false)
.toString();
public int compareTo(GuavaTest o) {
return ComparisonChain.start()
.compare(this.x, o.x)
.compare(this.y, o.y)
.result();
public static void countChinese(){
String str = new String(&abc中国cd你好啊89&);
String E1 = &[\u4e00-\u9fa5]&;// 中文
String E2 = &[a-zA-Z]&;// 英文
String E3 = &[0-9]&;// 数字
int chineseCount = 0;
int englishCount = 0;
int numberCount = 0;
System.out.println(&length = &+str.length());
System.out.println(&bytes length = &+str.getBytes().length);
for (int i = 0; i & str.length(); i++)
temp = String.valueOf(str.charAt(i));
if (temp.matches(E1))
chineseCount++;
if (temp.matches(E2))
englishCount++;
if (temp.matches(E3))
numberCount++;
System.out.println(&汉字数:& + chineseCount);
System.out.println(&英文数:& + englishCount);
System.out.println(&数字数:& + numberCount);
System.out.println(&特殊字符:& + (str.length() - (chineseCount + englishCount + numberCount)));
public static void countFile(String filename) throws IOException{
File file = new File(filename);
List&String& lines = Files.readLines(file, Charsets.UTF_8);
String E1 = &[\u4e00-\u9fa5]&;// 中文
String E2 = &[a-zA-Z]&;// 英文
String E3 = &[0-9]&;// 数字
String E4 = & &;
int chineseCount = 0;
int englishCount = 0;
int numberCount = 0;
int spaceCount = 0;
int lineCount = 0;
TreeMultiset&String& chineseWordsCount = TreeMultiset.create(),
englishWordsCount = TreeMultiset.create(),
numberWordsCount = TreeMultiset.create();
for(String line : lines){
lineCount ++;
line = line.toLowerCase();
for(int i=0; i&line.length(); i++){
String word = String.valueOf(line.charAt(i));
if(word.matches(E1)){
chineseCount++;
chineseWordsCount.add(word);
}else if(word.matches(E2)){
englishCount++;
englishWordsCount.add(word);
}else if(word.matches(E3)){
numberCount++;
numberWordsCount.add(word);
}else if(word.matches(E4)){
spaceCount++;
System.out.println(&数字:&+numberCount+&个&);
System.out.println(&字母:&+englishCount+&个&);
System.out.println(&汉字:&+chineseCount+&个&);
System.out.println(&空格:&+spaceCount+&个&);
System.out.println(&行数:&+lineCount+&行\n&);
for(String word: numberWordsCount.elementSet()){
System.out.println(&数字&+word+&:&+numberWordsCount.count(word)+&个&);
for(String word: englishWordsCount.elementSet()){
System.out.println(&字母&+word+&:&+englishWordsCount.count(word)+&个&);
for(String word: chineseWordsCount.elementSet()){
System.out.println(&汉字&+word+&:&+chineseWordsCount.count(word)+&个&);
public static void countCodeLines(String filename) throws IOException{
int linesCount = 0;
File file = new File(filename);
List&String& lines = Files.readLines(file, Charsets.UTF_8);
boolean incomment =
String tab = &\\s+&;
for(String line : lines){
line = line.trim();
if(line.startsWith(&//&)||line.equals(&&))
if(!incomment&&!line.startsWith(&/*&)){
linesCount ++ ;
if(line.contains(&/*&)){
incomment =
if(incomment&&line.contains(&*/&)){
incomment =
line = line.substring(line.indexOf(&*/&)+2).trim();
if(line!=&&&&!line.startsWith(&//&)){
linesCount ++;
System.out.println(linesCount);
public static void main(String [] args) throws IOException{
countFile(&./src/main/java/MyTest/MyTest/myguava/GuavaTest.java&);
countCodeLines(&./src/main/java/MyTest/MyTest/myguava/TestClass.java&);
int count = 0;
System.out.println(!true&&(count++ == 0));
String line = &8&;
System.out.println(line.substring(8));
String s =/**
Optional&String& possible = Optional.fromNullable(s);
System.out.println(possible.isPresent());
Preconditions.checkNotNull(s, &s is null&);
System.out.println(new GuavaTest(1, 1));
GuavaTest g = new GuavaTest(1, 1), g2 = new GuavaTest(1, 2);
System.out.pareTo(g2));
Ordering&Item& order = Ordering.natural().onResultOf(new Function&Item, Integer&(){
public Integer apply(Item input) {
return input.x;
List&Item& list = new ArrayList&Item&();
list.add(new Item(9));
list.add(new Item(2));
list.add(new Item(10));
List&Item& tmp = order.sortedCopy(list);
System.out.println(tmp);
ImmutableSet&String& set = ImmutableSet.of(&a&, &b&, &c&);
for(String s: set){
System.out.println(&+&+s);
Multiset&String& mset = HashMultiset.create();
mset.add(&a&);
mset.add(&b&);
mset.add(&c&);
mset.add(&a&);
for(String s: mset){
System.out.println(&+&+s);
System.out.println(mset.count(&a&));
BiMap&String, Integer& userId = HashBiMap.create();
userId.put(&a&, 1);
userId.put(&a&, 2);
userId.put(&b&, 3);
System.out.println(userId.get(&a&));
System.out.println(userId.inverse().get(1));
5、文件替换:
写一个程序, 读入 template.txt 和 env.properties
将template 中 ${NAME}表达式里的变量替换为env里设定的值. 然后输出到一个文件里.
第一个变量是: ${webwork.jsp.include_flush}
第二个变量是: ${webwork.i18n.encoding}
第三个第四个变量分别是: ${webwork.ui.templateSuffix}和${webwork.ui.notfound}
public class TemplateReplaceTest {
public static void replace() throws IOException{
String template = &./source/template.txt&, env = &./source/env.properties&, output = &./source/output.txt&;
File templateFile = new File(template);
List&String& lines = Files.readLines(templateFile, Charsets.UTF_8);
Properties prop = new Properties();
FileInputStream in = new FileInputStream(new File(env));
prop.load(in);
in.close();
StringBuffer buffer = new StringBuffer();
for(String line: lines){
line = line.trim();
String name = line.substring(2, line.length()-1).trim();
buffer.append(&${&);
buffer.append(prop.getProperty(name, &&));
buffer.append(&}\n&);
Files.write(buffer.toString().getBytes(), new File(output));
public static void main(String [] args) throws IOException{
String s = &0123456&;
System.out.println(s.substring(2, s.length()-1));
replace();
6、神雕文件替换:
/svn/fresh/javabase/branches/java-base-1/src/main/resources/
写一个程序,读入 sdxl.txt 和 env.properties,
将sdxl.txt中 ${NAME}表达式里的变量替换为env里设定的值,然后输出到一个文件里.
7、神雕文件替换:
现有2个文件,地址在:
1) /sites/task3.txt
2) /sites/task3_prop.txt
根据task3_prop.txt中内容替换掉task3.txt 里$function(index)形式文字,将其还原成一本完整小说。
其中function有4种函数,替换规则如下:
1) natureOrder 自然排序,即文本中排列顺序
2) indexOrder 索引排序,文本中每行第一个数字为索引
3) charOrder 文本排序,java的字符排序
4) charOrderDESC 文本倒序,java的字符倒序
注意:txt文件需要程序中现读现解析,而不是下载成本地文件。
最终转换过来的文件大小是:。
public class ShendiaoReplace {
private static final String task3Url = &/sites/task3.txt&;
private static final String taskPropUrl = &/sites/task3_prop.txt&;
private static final String output = &./source/output.txt&;
private LinkedList&String& keyList = Lists.newLinkedList();
private HashMap&String, String& keyMap = Maps.newHashMap();
public static List&String& readContext(String url) throws IOException{
URL myUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)myUrl.openConnection();
conn.setDoInput(true);
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
List&String& list = Lists.newLinkedList();
String s =
while((s=br.readLine())!=null){
list.add(s);
public void processTask3Prop() throws IOException{
List&String& list = readContext(taskPropUrl);
for(String line: list){
line = line.trim();
if(line.equals(&&))
System.out.println(line);
Iterable&String& items = Splitter.on(& &)
.omitEmptyStrings()
.split(line);
System.out.println(items);
Iterator&String& i = items.iterator();
String index = i.next(), words = i.next();
keyList.add(words);
keyMap.put(index, words);
public static class FunctionDesc{
int start,
String functionN
public FunctionDesc(int s, int e, String name, String index){
this.start =
this.end =
this.functionName =
this.index =
public String toString(){
return &[start = &+start+&, end = &+end+&, functionName = &+functionName + &, index = &+index+&]&;
public List&FunctionDesc& processTask3Line(String line){
List&FunctionDesc& funtionList = Lists.newArrayList();
int index = -1, prev = -1;
while((index = line.indexOf(&$&, prev+1))!=-1){
int tmpEnd = line.indexOf(&(&, index);
String name = line.substring(index+1, tmpEnd);
int end = line.indexOf(&)&, tmpEnd);
String indexS = line.substring(tmpEnd+1, end);
funtionList.add(new FunctionDesc(index, end, name, indexS));
return funtionL
public String function(String functionName, String indexName, int i){
boolean desc =
if(functionName.equals(&natureOrder&)){
return keyList.get(i);
}else if(functionName.equals(&indexOrder&)){
return keyMap.get(indexName);
}else if(functionName.equals(&charOrderDESC&)){
String [] items = keyList.get(i).split(&&);
Arrays.sort(items);
Arrays.sort(items, new Comparator&String&(){
public int compare(String o1, String o2) {
return -o1.compareTo(o2);
StringBuffer buffer = new StringBuffer();
for(String item: items){
buffer.append(item);
return buffer.toString();
public void replaceShendiao() throws IOException{
this.processTask3Prop();
List&String& taskLines = readContext(task3Url);
StringBuffer buffer = new StringBuffer();
int index = 0;
for(String line : taskLines){
line = line.trim();
if(line.equals(&&)) {
buffer.append(&\n&);
List&FunctionDesc& items = this.processTask3Line(line);
int last = 0;
StringBuffer tmpLine = new StringBuffer();
int prev = -1;
for(FunctionDesc fun: items){
tmpLine.append(line.substring(prev+1, fun.start));
tmpLine.append(function(fun.functionName, fun.index, index++));
prev = fun.
last = fun.
tmpLine.append(line.substring(last+1));
tmpLine.append(&\n&);
buffer.append(tmpLine);
String context = buffer.toString();
System.out.println(&最终转换过来的文件大小是:&+context.length());
Files.write(context.getBytes(), new File(output));
public static void main(String [] args) throws IOException{
System.out.println(readContext(&/sites/task3.txt&));
ShendiaoReplace shen = new ShendiaoReplace();
shen.processTask3Prop();
System.out.println(shen.keyList);
System.out.println(shen.keyMap);
String line = &当下手臂一缩一圈,使出母亲所授的小$natureOrder(72)夫,手掌打当下手臂一缩一圈,使出母亲所授的小$naturefasdOrder(72)夫,手掌打&;
System.out.println(line);
System.out.println(shen.processTask3Line(line));
shen.replaceShendiao();
System.out.println(line.indexOf(&$&));
1、输入年份,如2014,打印出该年万年历,以及标识出当天日期。类似于linux下的cal -y结果。
public class Calendar {
public static boolean isLeapYear(int year){
boolean leapYear =
if(year%100==0&&year%400==0){
leapYear =
}else if(year%100!=0&&year%4==0){
leapYear =
return leapY
* 以日,周四,为基准
* @param year
public static int countDays(int year){
int days = 0;
int start = 2015;
if(start&end){
end = 2015;
for(int i= i& i++){
if(isLeapYear(i)){
days += 366;
days +=365;
public static void showCalendar(int year){
int days = countDays(year);
int weekDay = days%7;
if(year&=2015){
weekDay = (weekDay+4)%7;
weekDay = 4 - weekD
if(weekDay&0){
weekDay += 7;
String [] monthLabels = new String[]{&January&, &February&, &March&, &April&, &May&, &June&, &July&, &August&, &September&, &October&, &November&, &December&};
String [] labels = new String[]{&Su&, &Mo&, &Tu&, &We&, &Th&, &Fr&, &Sa&};
for(int i=1; i&=12; i++){
System.out.println(&\n\n&+monthLabels[i-1]);
for(String label: labels){
System.out.print(label+& &);
System.out.println();
int monthDays = 30;
if(i==1||i==3||i==5||i==7||i==8||i==10||i==12){
monthDays = 31;
}else if(i==2){
if(isLeapYear(year)){
monthDays = 29;
}else monthDays = 28;
for(int j=0; j&weekD j++){
System.out.print(&
for(int j=1; j&=monthD j++){
if((j+weekDay-1)%7==0) System.out.println();
System.out.print(j+& &);
weekDay = (weekDay+monthDays) % 7;
public static void main(String [] args){
showCalendar(2013);
public class Calendar
public static boolean isLeapYear(int year){
boolean leapYear =
if(year%100==0&&year%400==0){
leapYear =
}else if(year%100!=0&&year%4==0){
leapYear =
return leapY
* 以日,周四,为基准
* @param year
public static int countDays(int year){
int days = 0;
int start = 2015;
if(start&end){
end = 2015;
for(int i= i& i++){
if(isLeapYear(i)){
days += 366;
days +=365;
public static void showCalendar(int year){
int days = countDays(year);
int weekDay = days%7;
if(year&=2015){
weekDay = (weekDay+4)%7;
weekDay = 4 - weekD
if(weekDay&0){
weekDay += 7;
String [] monthLabels = new String[]{&January&, &February&, &March&, &April&, &May&, &June&, &July&, &August&, &September&, &October&, &November&, &December&};
String [] labels = new String[]{&Su&, &Mo&, &Tu&, &We&, &Th&, &Fr&, &Sa&};
List&StringBuffer& lines =
for(int l=1; l&=4; l++){
lines = new LinkedList&StringBuffer&();
int s = (l-1)*3 + 1, e = l*3;
for(int i=s; i&=e; i++){
int lineCount = 0, size = lines.size();
StringBuffer tmpLine =
if(size&=lineCount){
tmpLine = new StringBuffer();
lines.add(tmpLine);
tmpLine = lines.get(lineCount);
tmpLine.append(&\t\t&);
tmpLine.append(monthLabels[i-1]+&\t\t\t\t\t\t&);
lineCount = 1;
size = lines.size();
if(size&=lineCount){
tmpLine = new StringBuffer();
lines.add(tmpLine);
tmpLine = lines.get(lineCount);
tmpLine.append(&\t\t&);
for(String label: labels){
tmpLine.append(label + &\t&);
int monthDays = 30;
if(i==1||i==3||i==5||i==7||i==8||i==10||i==12){
monthDays = 31;
}else if(i==2){
if(isLeapYear(year)){
monthDays = 29;
}else monthDays = 28;
boolean firstLoop =
for(int j=1; j&=monthD j++){
if((j+weekDay-1)%7==0||firstLoop){
lineCount ++;
size = lines.size();
if(size&=lineCount){
tmpLine = new StringBuffer();
lines.add(tmpLine);
int emptyMonths = i -
for(int em=0; em&emptyM em++){
tmpLine.append(&\t\t\t\t\t\t\t\t\t&);
tmpLine = lines.get(lineCount);
tmpLine.append(&\t\t&);
if(firstLoop){
for(int fi=0; fi&weekD fi++){
tmpLine.append(&\t&);
firstLoop =
tmpLine.append(j+&\t&);
int restDays = 35-monthDays-weekD
if(restDays&0){
if(restDays&=7){
lineCount ++;
size = lines.size();
if(size&=lineCount){
tmpLine = new StringBuffer();
lines.add(tmpLine);
int emptyMonths = i -
for(int em=0; em&emptyM em++){
tmpLine.append(&\t\t\t\t\t\t\t&);
tmpLine = lines.get(lineCount);
if(restDays&=7){
tmpLine.append(&\t\t&);
for(int j=0; j&(35-monthDays-weekDay); j++){
tmpLine.append(&\t&);
weekDay = (weekDay+monthDays) % 7;
for(StringBuffer sbline: lines){
System.out.println(sbline);
System.out.println();
public static void main(String [] args){
showCalendar(2015);
2、文件统计:&1) 按照附件第一列分组,输出类似于a -&c f(有去重)2) 统计每个字母出现的次数附件内容:b a ca c fb f ac d ea c cd e f
public class Count {
private final static String input = &./source/task2.txt&;
public static void count() throws IOException{
List&String& lines = Files.readLines(new File(input), Charsets.UTF_8);
Multimap&Character, Character& maps = HashMultimap.create();
for(String line: lines){
line = line.trim();
if(line.equals(&&))
Iterable&String& chars = Splitter.on(& &).split(line);
Iterator&String& iter = chars.iterator();
Character key = iter.next().charAt(0),
v1 = iter.next().charAt(0),
v2 = iter.next().charAt(0);
maps.put(key, v1);
maps.put(key, v2);
for(Character key: maps.keySet()){
System.out.print(key+& -& &);
Iterable&Character& values = maps.get(key);
Ordering&Character& order = Ordering.natural();
List&Character& list = order.sortedCopy(values);
for(Character v: list){
System.out.print(v+& &);
System.out.println();
public static void main(String [] args) throws IOException{
3、jvm提供了一个jstack的工具,可以把该jvm中运行的线程堆栈导出,具体见j.stack文件&
&DubboServerHandler-192.168.6.96:20880-thread-143& daemon prio=10 tid=0x6d000 nid=0x1807 waiting on condition [0xcfa000]
&java.lang.Thread.State: WAITING (parking)
&at sun.misc.Unsafe.park(Native Method)
&- parking to wait for &0xc16b630& (a java.util.concurrent.SynchronousQueue$TransferStack)
&at java.util.concurrent.locks.LockSupport.park(LockSupport.java:158)
&at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:422)
&at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:323)
&at java.util.concurrent.SynchronousQueue.take(SynchronousQueue.java:857)
&at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:947)
&at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
&at java.lang.Thread.run(Thread.java:619)
DubboServerHandler-192.168.6.96:20880-thread-143为线程的名字,tid为线程id ,java.lang.Thread.State: WAITING,WAITING为线程状态
waiting on condition [0xcfa000]表示该线程waiting在tid=0xcfa000的线程上
请写一个程序,解析出线程名,线程id,线程状态,以及哪些线程wait在同一个condition上 。就是说匹配“waiting on condition”的线程进行统计。
输出结果按照等待同一个condition的线程数从大到小排序。
输出格式如下:
condition id,count:
线程id|线程名|线程状态
线程id|线程名|线程状态
线程id|线程名|线程状态
condition id,count:
线程id|线程名|线程状态
线程id|线程名|线程状态
j.stack在:
/pages/viewpageattachments.action?pageId=5570576&metadataLink=true
public class CountJStack {
static class ThreadItem{
String threadN
public ThreadItem(String name, String id, String state, String condition){
this.threadName =
this.tid =
this.state =
this.condition =
public boolean equals(Object obj) {
if(!(obj instanceof ThreadItem))
ThreadItem item = (ThreadItem)
return this.tid.equals(item.tid);
public String toString(){
//线程id|线程名|线程状态
return &线程& + this.tid + &|&+this.threadName+&|&+
static class CounterLine implements LineProcessor&Multimap&String, ThreadItem&& {
private static final String stateString = &java.lang.Thread.State:&;
Multimap&String, ThreadItem& maps = HashMultimap.create();
boolean inblock =
StringBuffer buffer = new StringBuffer();
public void processBlock(String block){
int s = block.indexOf(&\&&), e = block.indexOf(&\&&, s+1);
String name = block.substring(s+1, e);
s = block.indexOf(&tid=&);
e = block.indexOf(& &, s);
String tid = block.substring(s+4, e);
s = block.indexOf(&[&);
e = block.indexOf(&]&, s);
String condition = block.substring(s+1, e).trim();
s = block.indexOf(stateString);
e = block.indexOf(&\n&, s);
String state = block.substring(s+stateString.length(), e);
ThreadItem item = new ThreadItem(name, tid, state, condition);
maps.put(condition, item);
}catch(Exception e){
//do nothing
public boolean processLine(String line) throws IOException {
line = line.trim();
if(inblock&&(line.equals(&&)||line.startsWith(&\&&))){
this.processBlock(buffer.toString());
buffer.delete(0, buffer.length());
if(line.startsWith(&\&&)){
buffer.append(line);
buffer.append(&\n&);
if(!inblock&&!line.startsWith(&\&&))
if(!inblock&&line.startsWith(&\&&)){
if(inblock){
buffer.append(line);
buffer.append(&\n&);
public Multimap&String, ThreadItem& getResult() {
public static void main(String[] args) throws IOException {
String testFilePath = &./source/j.stack&;
File testFile = new File(testFilePath);
CounterLine counter = new CounterLine();
Files.readLines(testFile, Charsets.UTF_8, counter);
Multimap&String, ThreadItem& maps = counter.getResult();
for(String condition: maps.keySet()){
Iterable&ThreadItem& iters = maps.get(condition);
List&ThreadItem& list = Lists.newArrayList(iters);
System.out.println(&condition &+condition+&, &+list.size()+&:&);
for(ThreadItem item: list){
System.out.println(item);
4、输入:给定一个hotelinfo文件,文件格式如下:&
shanghai_city_7208 上海全季酒店淮海路店
shanghai_city_14744 锦江之星上海金山城市沙滩店
jinan_2794 章丘市大众旅馆
carmel_ca_5 Carmel River Inn
格式说明:
1)一共两列,之间使用tab分隔
2)第一列是酒店代号,第二列是酒店名称
3)以shanghai_city_7208为例,前面的shanghai_city代表城市
要求如下:
1. 输出一个文件,和hotelinfo格式一样,但是按照酒店代号进行降序排序
2. 输出一个文件,两列,第一列是城市代号,第二列是这个城市下的酒店数,但是按照酒店数进行降序排序
hotelinfo文件在:/download/attachments/4850688/hotelinfo.txt?version=2&modificationDate=0&api=v2
public class HotelInfo {
private static final String input = &./source/hotelinfo&,
output1 = &./source/hotel1.txt&,
output2 = &./source/hotel2.txt&;
@SuppressWarnings(&unchecked&)
public static void processHotel(){
TreeMap&String, String& maps = Maps.newTreeMap();
Multiset&String& sets = HashMultiset.create();
FileInputStream inputStream =
Scanner sc =
inputStream = new FileInputStream(input);
sc = new Scanner(inputStream, &UTF-8&);
while (sc.hasNextLine()) {
String line = sc.nextLine();
String [] items = line.split(&\t&);
maps.put(items[0], items[1]);
int e = items[0].lastIndexOf(&_&);
sets.add(items[0].substring(0, e));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Set&String& keys = maps.descendingKeySet();
StringBuffer buffer = new StringBuffer();
for(String key: keys){
buffer.append(key);
buffer.append(&\t&);
buffer.append(maps.get(key)+&\n&);
Files.write(buffer.toString().getBytes(), new File(output1));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
HashMap&String, Integer& tmpMap = Maps.newHashMap();
for(String key: sets.elementSet()){
tmpMap.put(key, sets.count(key));
List&Map.Entry&String, Integer&& list = new LinkedList&Map.Entry&String, Integer&&(tmpMap.entrySet());
Collections.sort(list, new Comparator() {
//将链表按照值得从大到小进行排序
public int compare(Object o1, Object o2) {
Map.Entry&String, Integer& e1 = (Map.Entry&String, Integer&)o1,
e2 = (Map.Entry&String, Integer&)o2;
return -e1.getValue().compareTo(e2.getValue());
buffer.delete(0, buffer.length());
for(Map.Entry&String, Integer& entry: list){
buffer.append(entry.getKey());
buffer.append(&\t&);
buffer.append(entry.getValue());
buffer.append(&\n&);
Files.write(buffer.toString().getBytes(), new File(output2));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
public static void main(String[] args) throws IOException {
processHotel();
5、以下格式 ~ 100表示入住,离店,入住一天的价格是¥100。&
现有文件中包含多行这样的日期价格段,请将其合并,合并的规则包括:
1)价格相同,日期段相邻或者重叠的需要合并
2)相同日期的价格已后面录入的为准
合并后就是
合并之后就是
请读入指定文件price.txt和data.txt,并将所有的日期价格段合并后,按照入住日期升序展示,输出到控制台即可。
public class DateMerge {
private final static String pricefile = &./source/price.txt&;
public static void processPrice() throws IOException, ParseException{
List&String& lines = Files.readLines(new File(pricefile), Charsets.UTF_8);
RangeMap&Date, Integer& rangeMap = TreeRangeMap.create();
SimpleDateFormat format = new SimpleDateFormat(&yyyy-MM-dd&);
for(String line: lines){
line = line.trim();
if(line.equals(&&))
String [] items = line.split(& &);
String [] dates = items[0].split(&~&);
Date s = format.parse(dates[0]),
e = format.parse(dates[1]);
Date bs = new Date(s.getTime()-24*),
ae = new Date(e.getTime()+24*);
int value = Integer.parseInt(items[1]);
Entry&Range&Date&, Integer& entryS = rangeMap.getEntry(bs),
entryE = rangeMap.getEntry(ae);
if(entryS!=null&&entryS.getValue().equals(value)){
rangeMap.remove(entryS.getKey());
s = entryS.getKey().lowerEndpoint();
if(entryE!=null&&entryE.getValue().equals(value)){
rangeMap.remove(entryE.getKey());
e = entryE.getKey().upperEndpoint();
rangeMap.put(Range.closed(s, e), value);
Map&Range&Date&, Integer& rangeDateMap = rangeMap.asMapOfRanges();
Set&Entry&Range&Date&, Integer&& entries = rangeDateMap.entrySet();
Iterator&Entry&Range&Date&, Integer&& iterator = entries.iterator();
while(iterator.hasNext()){
Entry&Range&Date&, Integer& next = iterator.next();
System.out.println(next.getKey() + &\t& + next.getValue());
public static void main(String [] args) throws IOException, ParseException{
processPrice();
&/pre&&pre code_snippet_id=&682832& snippet_file_name=&blog__3897997& name=&code& class=&java&&6、假设我们有一个类HotelCenter,它有方法List&Hotel& getHotelList(String city)可以获得一个城市下所有酒店列表,
Hotel类有如下属性String name, String address, int price, Map&String, String& properties
酒店的非name和address的属性都可以通过properties.get(key)得到
我们需要实现以下功能
根据页面传入的参数返回对应的酒店列表,参数键值对会以&分割,参数的值如果有多个,会有逗号分隔
下述任何参数都可能缺失,对应的值如果为空串,也当做该参数不存在处理
参数会分三部分组成,过滤参数、排序参数和翻页参数
过滤参数包括
city(酒店所在城市)
name(酒店名包括name的值)
address(酒店地址包括address的值)
brand(酒店品牌属于brand的值的一个)
star(酒店星级属于star的值中的一个)
price(酒店价格在price值区间范围内)
area(酒店所属区域等于area值中的一个)
排序参数包括
sort(按照sort的值进行排序,如果值是price,就按照价格进行排序,如果值是star,则按照星级进行排序)
order(值如果是asc就是升序,是desc就是降序)
排序参数缺失时,默认按照sort=price&order=asc处理
翻页参数包括
page(page的值是需要看的酒店其实索引值和终止索引值,是左闭右开,如果选择的索引没有数据,则不处理,比如一共有30个酒店,page=20-40,需要返回后10个酒店)
翻页参数缺失时,默认按照0-20处理
以下是一个请求参数的例子
city=北京&name=酒店&address=海淀黄庄&brand=7天,如家&star=3,4&price=100-200,300-500&area=中关村&sort=price&order=desc&page=100-120
7、完成如下功能:
1)有一个(任意)对象,里面有N个properties以及getter和setter方法
2)有一个properties文件,有N个key,value来描述对象中property的值
3)有一个scheme固定的xml,用来描述这个对象
要求写一个解析器:
1)将xml中的占位符,替换为properties文件中的value
2) 将xml解析成对象,调用getter方法的时候可以获得值
3)用面向对象的思想,使该解析器有扩展性
例子见附件,注意:
1)对象是任意对象,不是例子中的Student,对象中的property都是java中的原生类型
2)xml和properties在使用的时候都是根据对象配置好的
3) xml的scheme是固定的,就是附件中的scheme
相关文件在:/pages/viewpage.action?pageId=7439502
public class Student {
public String getName() {
public void setName(String name) {
this.name =
public int getAge() {
public void setAge(int age) {
this.age =
public Date getBirth() {
public void setBirth(Date birth) {
this.birth =
public String toString(){
return &[ name = & + name +& , age = &+age+& , birth = & + birth+&]&;
}&/pre&&pre code_snippet_id=&682832& snippet_file_name=&blog__8663109& name=&code& class=&java&&&pre name=&code& class=&java&&public class RecoverObject&O& {
private String propertiesF
private String objectXmlF
private String recoverObjextXmlF
private String clazzN
public RecoverObject(String propertiesFile, String objectXmlFile){
this.propertiesFile = propertiesF
this.objectXmlFile = objectXmlF
this.recoverObjextXmlFile = this.objectXmlFile+&.recover&;
this.properties = new Properties();
initObject();
private void processXmlFile(String context){
int pre = -1, s = -1, e = -1;
StringBuffer buffer = new StringBuffer();
while((s = context.indexOf(&${&, pre+1))!=-1){
e = context.indexOf(&}&, s + 2);
buffer.append(context.substring(pre+1, s));
String attr = context.substring(s+2, e);
buffer.append(this.properties.get(attr));
buffer.append(context.substring(pre+1));
Files.write(buffer.toString().getBytes(), new File(this.recoverObjextXmlFile));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
private void initObject(){
FileInputS
in = new FileInputStream(new File(this.propertiesFile));
this.properties.load(in);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
StringBuffer buffer = new StringBuffer();
Scanner scan = new Scanner(new FileInputStream(new File(this.objectXmlFile)));
while(scan.hasNextLine()){
buffer.append(scan.nextLine());
buffer.append(&\n&);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
String context = buffer.toString();
this.processXmlFile(context);
public O get(){
SAXBuilder builder=new SAXBuilder(false);
Class&?& demo=
Document doc=builder.build(this.recoverObjextXmlFile);
Element object=doc.getRootElement();
this.clazzName = object.getAttributeValue(&class&);
demo=Class.forName(this.clazzName);
O o = (O) demo.newInstance();
List propertiesList = object.getChildren(&property&);
for(Iterator iter = propertiesList.iterator(); iter.hasNext();){
Element attr = (Element) iter.next();
String attrName = attr.getAttributeValue(&name&);
String attrValue = attr.getChildText(&value&);
Field f= demo.getDeclaredField(attrName);
f.setAccessible(true);
Class&?& type = f.getType();
if(type.equals(String.class)){
f.set(o, attrValue);
}else if(type.equals(int.class)){
f.set(o, Integer.parseInt(attrValue));
}else if(type.equals(java.util.Date.class)){
SimpleDateFormat format = new SimpleDateFormat(&yyyy-MM-dd&);
f.set(o, format.parse(attrValue));
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
public static void main(String [] args){
RecoverObject&Student& object = new RecoverObject&Student&(&./source/object.properties2&, &./source/object.xml&);
Student s = object.get();
System.out.println(s);
版权声明:本文为博主原创文章,未经博主允许不得转载。
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:577107次
积分:7036
积分:7036
排名:第1400名
原创:187篇
转载:227篇
评论:63条
(12)(1)(1)(6)(3)(7)(2)(8)(27)(8)(7)(4)(11)(29)(19)(25)(9)(5)(5)(8)(8)(4)(4)(32)(17)(6)(3)(3)(25)(4)(8)(9)(9)(21)(12)(9)(3)(8)(4)(1)(18)(6)(2)}

我要回帖

更多关于 10个数字排列组合 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信