1、有这样一个Room类:
public class Room {
/**
* 房间名称
*/
private String roomName;
/**
* 房间面积
*/
private int area;
/**
* 房间价格
*/
private BigDecimal price;
/**
* 酒店的地址
*/
private String address;
/**
* 酒店的电话
*/
private String phoneNumber
}
还有这样一个Person类:
public class Person {
/**
* 姓名
*/
private String username;
/**
* 年龄
*/
private int age;
/**
* 体重
*/
private int weight;
}
现在我们需要用HashMap做一个以room为key,以person为value的缓存,以提供快速查询指定房间入住了哪些人?
2、根据指定项目目录下(可以认为是java源文件目录)中,统计被import最多的类。
1) 查找一个目录下,所有文件中数字、字母(大小写不区分)、汉字、空格的个数、行数。
2) 将结果数据写入到文件中。
文件格式如下:
数字:198213个
字母:18231个
汉字:1238123个
空格:823145个
行数:99812行
数字0:123个
数字1:1214个
数字2:23423个
……
字母A:754456个
数字B:7567个
数字C:456456个
......
4、统计附件中的StringUtils.java文件的有效代码行数。
1) 有效不包括空行、注释
2) 考虑代码里有多行注释的情况
5、文件替换:
写一个程序, 读入 template.txt 和 env.properties
将template 中 ${NAME}表达式里的变量替换为env里设定的值. 然后输出到一个文件里.
第一个变量是: ${webwork.jsp.include_flush}
第二个变量是: ${webwork.i18n.encoding}
第三个第四个变量分别是: ${webwork.ui.templateSuffix}和${webwork.ui.notfound}
6、神雕文件替换:
http://fresh.qunar.com/svn/fresh/javabase/branches/java-base-1/src/main/resources/
写一个程序,读入 sdxl.txt 和 env.properties,
将sdxl.txt中 ${NAME}表达式里的变量替换为env里设定的值,然后输出到一个文件里.
7、神雕文件替换:
现有2个文件,地址在:
1) http://fresh.qunar.com/sites/task3.txt
2) http://fresh.qunar.com/sites/task3_prop.txt
要求:
根据task3_prop.txt中内容替换掉task3.txt 里$function(index)形式文字,将其还原成一本完整小说。
其中function有4种函数,替换规则如下:
1) natureOrder 自然排序,即文本中排列顺序
2) indexOrder 索引排序,文本中每行第一个数字为索引
3) charOrder 文本排序,java的字符排序
4) charOrderDESC 文本倒序,java的字符倒序
注意:txt文件需要程序中现读现解析,而不是下载成本地文件。
最终转换过来的文件大小是:。
1、输入年份,如2014,打印出该年万年历,以及标识出当天日期。类似于linux下的cal -y结果。
2、文件统计: 1) 按照附件第一列分组,输出类似于a ->c f(有去重)2) 统计每个字母出现的次数附件内容:b a ca c fb f ac d ea c cd e f
3、jvm提供了一个jstack的工具,可以把该jvm中运行的线程堆栈导出,具体见j.stack文件
比如
"DubboServerHandler-192.168.6.96:20880-thread-143" daemon prio=10 tid=0x00007f3d8006d000 nid=0x1807 waiting on condition [0x00007f3d67cfa000]
java.lang.Thread.State: WAITING (parking)
at sun.misc.Unsafe.park(Native Method)
- parking to wait for <0x00007f3f7c16b630> (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 [0x00007f3d67cfa000]表示该线程waiting在tid=0x00007f3d67cfa000的线程上
请写一个程序,解析出线程名,线程id,线程状态,以及哪些线程wait在同一个condition上 。就是说匹配“waiting on condition”的线程进行统计。
输出结果按照等待同一个condition的线程数从大到小排序。
输出格式如下:
condition id,count:
线程id|线程名|线程状态
线程id|线程名|线程状态
线程id|线程名|线程状态
condition id,count:
线程id|线程名|线程状态
线程id|线程名|线程状态
……
j.stack在:
http://fresh.qunar.com/pages/viewpageattachments.action?pageId=5570576&metadataLink=true
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文件在:http://fresh.qunar.com/download/attachments/4850688/hotelinfo.txt?version=2&modificationDate=1373940019000&api=v2
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
public class Room {
/**
* 房间名称
*/
private String roomName;
/**
* 房间面积
*/
private int area;
/**
* 房间价格
*/
private BigDecimal price;
/**
* 酒店的地址
*/
private String address;
/**
* 酒店的电话
*/
private String phoneNumber
}
还有这样一个Person类:
public class Person {
/**
* 姓名
*/
private String username;
/**
* 年龄
*/
private int age;
/**
* 体重
*/
private int weight;
}
现在我们需要用HashMap做一个以room为key,以person为value的缓存,以提供快速查询指定房间入住了哪些人?
请完成一个可以运行的演示。
public class Person {
private String username;
private int age;
private int weight;
public Person(String name, int age, int weight){
this.username = name;
this.age = age;
this.weight = weight;
}
public boolean equals(Object obj) {
if(!(obj instanceof Person)) return false;
Person p = (Person)obj;
return this.username.equals(p.username)&&
this.age == p.age&&
this.weight == p.weight;
}
}
public class Room {
private String roomName;
private int area;
private BigDecimal price;
private String address;
private String phoneNumber;
public Room(String roomName, int area, BigDecimal price, String address, String phoneNumber){
this.roomName = roomName;
this.area = area;
this.price = price;
this.address = address;
this.phoneNumber = phoneNumber;
}
public int hashCode(){
// int result = roomName.hashCode();
// result = 31*result + area;
// 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)) return false;
Room tmpRoom = (Room)obj;
return this.address.equals(tmpRoom.address)&&
this.phoneNumber.equals(tmpRoom.phoneNumber)&&
this.roomName.equals(tmpRoom.roomName)&&
this.area==tmpRoom.area;
}
}
public class RoomCache {
HashMap<Room, Person> cache;
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 dirName;
HashMap<String, Integer> importClassRecords;
public MostImportClass(String dir){
this.dirName = dir;
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;
return value;
}
public void processFile(File file){
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
String line = null;
try {
while((line = reader.readLine()) != null){
line = line.trim();
if(line.startsWith("public")||line.startsWith("class")){
break;
}
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);
}else{
importClassRecords.put(className, value+1);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void statisticsClazz(File file){
if(!file.isDirectory()){
processFile(file);
}else{
File [] files = file.listFiles();
for(File tmpFile: files){
statisticsClazz(tmpFile);
}
}
}
public String getMostImportClazzName(){
int max = Integer.MIN_VALUE;
String clazzName = null;
for(Entry item: this.importClassRecords.entrySet()){
String key = (String) item.getKey();
int value = (Integer)item.getValue();
if(value>max){
max = value;
clazzName = key;
}
}
return clazzName;
}
}
1) 查找一个目录下,所有文件中数字、字母(大小写不区分)、汉字、空格的个数、行数。
2) 将结果数据写入到文件中。
文件格式如下:
数字:198213个
字母:18231个
汉字:1238123个
空格:823145个
行数:99812行
数字0:123个
数字1:1214个
数字2:23423个
……
字母A:754456个
数字B:7567个
数字C:456456个
......
class Item{
public int x;
public Item(int x){
this.x = x;
}
public String toString(){
return this.x+"";
}
}/**
* fjsdi
* @author Cool
*
*/public class GuavaTest implements Comparable<GuavaTest>{
int x;
int y;
public GuavaTest(int x, int y){
this.x = x;
this.y = y;
}
public String toString(){
String ss = MoreObjects.toStringHelper("GuavaTest")
.add("x", 12)
.add("b", false)
.toString();
return ss;
}
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;
String temp;
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 = false;
String tab = "\\s+";
for(String line : lines){
line = line.trim();
if(line.startsWith("//")||line.equals("")) continue;
if(!incomment&&!line.startsWith("/*")){
linesCount ++ ;
}
if(line.contains("/*")){
incomment = true;
}
if(incomment&&line.contains("*/")){
incomment = false;
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 = "012345*/678";
// System.out.println(line.substring(8));
// String s = null;/**
// 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.println(g.compareTo(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 int x;
public Item(int x){
this.x = x;
}
public String toString(){
return this.x+"";
}
}/**
* fjsdi
* @author Cool
*
*/public class GuavaTest implements Comparable<GuavaTest>{
int x;
int y;
public GuavaTest(int x, int y){
this.x = x;
this.y = y;
}
public String toString(){
String ss = MoreObjects.toStringHelper("GuavaTest")
.add("x", 12)
.add("b", false)
.toString();
return ss;
}
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;
String temp;
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 = false;
String tab = "\\s+";
for(String line : lines){
line = line.trim();
if(line.startsWith("//")||line.equals("")) continue;
if(!incomment&&!line.startsWith("/*")){
linesCount ++ ;
}
if(line.contains("/*")){
incomment = true;
}
if(incomment&&line.contains("*/")){
incomment = false;
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 = "012345*/678";
// System.out.println(line.substring(8));
// String s = null;/**
// 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.println(g.compareTo(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、神雕文件替换:
http://fresh.qunar.com/svn/fresh/javabase/branches/java-base-1/src/main/resources/
写一个程序,读入 sdxl.txt 和 env.properties,
将sdxl.txt中 ${NAME}表达式里的变量替换为env里设定的值,然后输出到一个文件里.
7、神雕文件替换:
现有2个文件,地址在:
1) http://fresh.qunar.com/sites/task3.txt
2) http://fresh.qunar.com/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 = "http://fresh.qunar.com/sites/task3.txt";
private static final String taskPropUrl = "http://fresh.qunar.com/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 = null;
while((s=br.readLine())!=null){
list.add(s);
}
return list;
}
public void processTask3Prop() throws IOException{
List<String> list = readContext(taskPropUrl);
for(String line: list){
line = line.trim();
if(line.equals("")) continue;
// 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, end;
String functionName;
String index;
public FunctionDesc(int s, int e, String name, String index){
this.start = s;
this.end = e;
this.functionName = name;
this.index = 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));
prev = index;
}
return funtionList;
}
public String function(String functionName, String indexName, int i){
boolean desc = false;
if(functionName.equals("natureOrder")){
return keyList.get(i);
}else if(functionName.equals("indexOrder")){
return keyMap.get(indexName);
}else if(functionName.equals("charOrderDESC")){
desc = true;
}
String [] items = keyList.get(i).split("");
if(desc){
Arrays.sort(items);
}else{
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");
continue;
}
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.end;
last = fun.end;
}
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("http://fresh.qunar.com/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 = false;
if(year%100==0&&year%400==0){
leapYear = true;
}else if(year%100!=0&&year%4==0){
leapYear = true;
}
return leapYear;
}
/**
* 以2015年1月1日,周四,为基准
* @param year
* @return
*/
public static int countDays(int year){
int days = 0;
int start = 2015;
int end = year;
if(start>end){
start = year;
end = 2015;
}
for(int i=start; i<end; i++){
if(isLeapYear(i)){
days += 366;
}else{
days +=365;
}
}
return days;
}
public static void showCalendar(int year){
int days = countDays(year);
int weekDay = days%7;
if(year>=2015){
weekDay = (weekDay+4)%7;
}else{
weekDay = 4 - weekDay;
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<weekDay; j++){
System.out.print(" ");
}
for(int j=1; j<=monthDays; 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 = false;
if(year%100==0&&year%400==0){
leapYear = true;
}else if(year%100!=0&&year%4==0){
leapYear = true;
}
return leapYear;
}
/**
* 以2015年1月1日,周四,为基准
* @param year
* @return
*/
public static int countDays(int year){
int days = 0;
int start = 2015;
int end = year;
if(start>end){
start = year;
end = 2015;
}
for(int i=start; i<end; i++){
if(isLeapYear(i)){
days += 366;
}else{
days +=365;
}
}
return days;
}
public static void showCalendar(int year){
int days = countDays(year);
int weekDay = days%7;
if(year>=2015){
weekDay = (weekDay+4)%7;
}else{
weekDay = 4 - weekDay;
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 = null;
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 = null;
if(size<=lineCount){
tmpLine = new StringBuffer();
lines.add(tmpLine);
}else{
tmpLine = lines.get(lineCount);
}
tmpLine.append("\t\t");
tmpLine.append(monthLabels[i-1]+"\t\t\t\t\t\t");
lineCount = 1;
size = lines.size();
tmpLine = null;
if(size<=lineCount){
tmpLine = new StringBuffer();
lines.add(tmpLine);
}else{
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 = true;
for(int j=1; j<=monthDays; j++){
if((j+weekDay-1)%7==0||firstLoop){
lineCount ++;
size = lines.size();
tmpLine = null;
if(size<=lineCount){
tmpLine = new StringBuffer();
lines.add(tmpLine);
int emptyMonths = i - s;
for(int em=0; em<emptyMonths; em++){
tmpLine.append("\t\t\t\t\t\t\t\t\t");
}
}else{
tmpLine = lines.get(lineCount);
}
tmpLine.append("\t\t");
}
if(firstLoop){
for(int fi=0; fi<weekDay; fi++){
tmpLine.append("\t");
}
firstLoop = false;
}
tmpLine.append(j+"\t");
}
int restDays = 35-monthDays-weekDay;
if(restDays>0){
if(restDays>=7){
lineCount ++;
}
size = lines.size();
tmpLine = null;
if(size<=lineCount){
tmpLine = new StringBuffer();
lines.add(tmpLine);
int emptyMonths = i - s;
for(int em=0; em<emptyMonths; em++){
tmpLine.append("\t\t\t\t\t\t\t");
}
}else{
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("")) continue;
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{
count();
}
}
3、jvm提供了一个jstack的工具,可以把该jvm中运行的线程堆栈导出,具体见j.stack文件
比如
"DubboServerHandler-192.168.6.96:20880-thread-143" daemon prio=10 tid=0x00007f3d8006d000 nid=0x1807 waiting on condition [0x00007f3d67cfa000]
java.lang.Thread.State: WAITING (parking)
at sun.misc.Unsafe.park(Native Method)
- parking to wait for <0x00007f3f7c16b630> (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 [0x00007f3d67cfa000]表示该线程waiting在tid=0x00007f3d67cfa000的线程上
请写一个程序,解析出线程名,线程id,线程状态,以及哪些线程wait在同一个condition上 。就是说匹配“waiting on condition”的线程进行统计。
输出结果按照等待同一个condition的线程数从大到小排序。
输出格式如下:
condition id,count:
线程id|线程名|线程状态
线程id|线程名|线程状态
线程id|线程名|线程状态
condition id,count:
线程id|线程名|线程状态
线程id|线程名|线程状态
……
j.stack在:
http://fresh.qunar.com/pages/viewpageattachments.action?pageId=5570576&metadataLink=true
public class CountJStack {
static class ThreadItem{
String threadName;
String tid;
String state;
String condition;
public ThreadItem(String name, String id, String state, String condition){
this.threadName = name;
this.tid = id;
this.state = state;
this.condition = condition;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof ThreadItem)) return false;
ThreadItem item = (ThreadItem)obj;
return this.tid.equals(item.tid);
}
public String toString(){
//线程id|线程名|线程状态
return "线程" + this.tid + "|"+this.threadName+"|"+state;
}
}
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 = false;
StringBuffer buffer = new StringBuffer();
public void processBlock(String block){
try{
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("\""))){
inblock = false;
this.processBlock(buffer.toString());
buffer.delete(0, buffer.length());
if(line.startsWith("\"")){
buffer.append(line);
buffer.append("\n");
inblock = true;
}
return true;
}
if(!inblock&&!line.startsWith("\"")) return true;
if(!inblock&&line.startsWith("\"")){
inblock = true;
}
if(inblock){
buffer.append(line);
buffer.append("\n");
}
return true;
}
public Multimap<String, ThreadItem> getResult() {
return maps;
}
}
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文件在:http://fresh.qunar.com/download/attachments/4850688/hotelinfo.txt?version=2&modificationDate=1373940019000&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 = null;
Scanner sc = null;
try {
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");
}
try {
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");
}
try {
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、以下格式 2013-10-01~2013-10-02 100表示2013-10-01入住,2013-10-02离店,入住一天的价格是¥100。
现有文件中包含多行这样的日期价格段,请将其合并,合并的规则包括:
1)价格相同,日期段相邻或者重叠的需要合并
2)相同日期的价格已后面录入的为准
例子1:
2013-08-01~2013-08-31 300
2013-08-25~2013-09-30 300
合并后就是
2013-08-01~2013-09-30 300
例子2:
2013-08-01~2013-12-31 300
2013-10-01~2013-10-07 500
合并之后就是
2013-08-01~2013-09-30 300
2013-10-01~2013-10-07 500
2013-10-08~2013-12-31 300
请读入指定文件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("")) continue;
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*3600*1000),
ae = new Date(e.getTime()+24*3600*1000);
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_20150603_15_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
相关文件在:http://fresh.qunar.com/pages/viewpage.action?pageId=7439502
public class Student {
private String name;
private int age;
private Date birth;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public String toString(){
return "[ name = " + name +" , age = "+age+" , birth = " + birth+"]";
}
}
</pre><pre code_snippet_id="682832" snippet_file_name="blog_20150603_17_8663109" name="code" class="java">
<pre name="code" class="java">public class RecoverObject<O> {
private String propertiesFile;
private String objectXmlFile;
private String recoverObjextXmlFile;
private String clazzName;
private Properties properties;
public RecoverObject(String propertiesFile, String objectXmlFile){
this.propertiesFile = propertiesFile;
this.objectXmlFile = objectXmlFile;
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));
pre = e;
}
buffer.append(context.substring(pre+1));
try {
Files.write(buffer.toString().getBytes(), new File(this.recoverObjextXmlFile));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
private void initObject(){
FileInputStream in;
try {
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();
try {
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=null;
try {
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));
}
}
return o;
} 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();
}
return null;
}
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);
}
}