Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Friday, December 23, 2016

Comparable 和Comparator的区别

Comparable是排序接口;若一个类实现了Comparable接口,就意味着“该类支持排序”。

而Comparator是比较器接口;我们若需要控制某个类的次序,可以新建一个“该类的比较器”来进行排序。

我们不难发现:Comparable相当于“内部比较器”,而Comparator相当于“外部比较器”。

下面两个例子是对Node的count值进行比较

Comparable写法
class Node implements Comparable<Node>{
    int num;
    int count;
    public Node(int num){
        this.count = 0;
        this.num = num;
    }
    @Override
    public int compareTo(Node o){
        return this.count - o.count;
    }
}

Comparator写法
 private Comparator<Node> cmp = new Comparator<Node>(){
        public int compare(Node a, Node b){
            return a.count - b.count;
        }
    };

Saturday, April 9, 2016

java read json

{
   "pageInfo": {
         "pageName": "abc",
         "pagePic": "http://example.com/content.jpg"
    },
    "posts": [
         {
              "post_id": "123456789012_123456789012",
              "actor_id": "1234567890",
              "picOfPersonWhoPosted": "http://example.com/photo.jpg",
              "nameOfPersonWhoPosted": "Jane Doe",
              "message": "Sounds cool. Can't wait to see it!",
              "likesCount": "2",
              "comments": [],
              "timeOfPost": "1234567890"
         }
    ]
}

Java code :

JSONObject obj = new JSONObject(responsejsonobj);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");

JSONArray arr = obj.getJSONArray("posts");
for (int i = 0; i < arr.length(); i++)
{
    String post_id = arr.getJSONObject(i).getString("post_id");
    ......etc
}

Monday, June 1, 2015

spring Mvc 之helloworld

eclipse 安装spring开发包:https://spring.io/tools/sts/all
并安装
下载日志记录器: http://mvnrepository.com/artifact/commons-logging/commons-logging
下载spring的包:http://repo.springsource.org/libs-release-local/org/springframework/spring/4.0.0.RELEASE/spring-framework-4.0.0.RELEASE-dist.zip

新建HelloWorld class
package edu.spring.beans;

public class HelloWorld {
private String name;
public void setNamex(String name){
this.name=name;
}
public void hello(){
System.out.println("hello "+name);
}

}

新建配置文件appContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloworld" class="edu.spring.beans.HelloWorld">
<property name="namex" value="Spring"></property></bean>
</beans>

新建Main class

public class Main {

public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("appContext.xml");
HelloWorld helloworld=(HelloWorld) ctx.getBean("helloworld");
helloworld.hello();
}

}


结果:

hello Spring

Friday, May 1, 2015

利用htmlunit和webdriver读取网页数据

先说.net的,需要进入 using mshtml;

           System.Net.WebClient webClient = new System.Net.WebClient();
              IWebDriver driver = new FirefoxDriver();
            driver.Navigate().GoToUrl("http://course.xxx.edu/");
            String pageSource = driver.PageSource;
这种比较笨重,需要启动firefox读取


对java的,需要使用htmlunit包
WebClient webClient = new WebClient(BrowserVersion.FIREFOX_31);
webClient.getOptions().setJavaScriptEnabled(true);
//webClient.getCookieManager().setCookiesEnabled(true);
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
webClient.getOptions().setThrowExceptionOnScriptError(false);
   webClient.getOptions().setCssEnabled(false);

   HtmlPage page =
webClient.getPage("http://course.xxx.edu");
 
webClient.waitForBackgroundJavaScript(5000);


String text=page.asText();
/*String patternString = "Available Seats:";
Pattern pattern = Pattern.compile(patternString);

        Matcher matcher = pattern.matcher(text);*/
        int index=text.lastIndexOf("Available Seats");
        String seats=text.substring(index+17, index+19).trim();

int numOfSeats=Integer.parseInt(seats);
System.out.println(numOfSeats);


如何利用c#发送gmail
public static void SendMail(String s)
        {
            MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
            mail.From = new MailAddress("sender@gmail.com");
            mail.To.Add("receiver@gmail.com");
           // mail.To.Add("m2@gmail.com");
            mail.Subject = "good news: "+s;
            mail.Body += " <html>";
            mail.Body += "<body>";
            mail.Body += "<table>";
            mail.Body += "<tr>";
            mail.Body += "<td>User Name : </td><td> HAi </td>";
            mail.Body += "</tr>";

            mail.Body += "<tr>";
            mail.Body += "<td>Password : </td><td>aaaaaaaaaa</td>";
            mail.Body += "</tr>";
            mail.Body += "</table>";
            mail.Body += "</body>";
            mail.Body += "</html>";
            mail.IsBodyHtml = true;
            SmtpServer.Port = 587;
            SmtpServer.Credentials = new System.Net.NetworkCredential("sender@gmail.com", "mypassword");
            SmtpServer.EnableSsl = true;
            SmtpServer.Send(mail);

        }

Monday, March 16, 2015

Java当中的常见同步方法

在进行多线程编程时,难免还要碰到两个问题,那就线程间的互斥与同步:
线程同步是指线程之间所具有的一种制约关系,一个线程的执行依赖另一个线程的消息,当它没有得到另一个线程的消息时应等待,直到消息到达时才被唤醒。线程互斥是指对于共享的进程系统资源,在各单个线程访问时的排它性。当有若干个线程都要使用某一共享资源时,任何时刻最多只允许一个线程去使用,其它要使用该资源的线程必须等待,直到占用资源者释放该资源。线程互斥可以看成是一种特殊的线程同步(下文统称为同步)。

线程间的同步方法大体可分为两类:用户模式和内核模式。顾名思义,内核模式就是指利用系统内核对象的单一性来进行同步,使用时需要切换内核态与用户态,而用户模式就是不需要切换到内核态,只在用户态完成操作。
用户模式下的方法有:原子操作(例如一个单一的全局变量),临界区。内核模式下的方法有:事件,信号量,互斥量。
方法1:使用同步法,该方法的核心在于synchronized (lock) 其中lock必须是一个对象。

public class CriticalSectionSynchronizedBlock
{
 static String message = "Now Is The Time For All Good Men\n";
 static int numThreads = 200;
 
 static Integer lock = 1;

 public static void main(String args[])
 {
  for (int idx = 0; idx < numThreads; idx++) {
   Thread t = new Thread(new StreamPrinter());
   t.start();
  }
 }

 static class StreamPrinter implements Runnable
 {
  @Override
  public void run()
  {
   while (true) {
    byte chars[] = message.getBytes();
    synchronized (lock) {
     for (int idx = 0; idx < chars.length; idx++) {
      byte achar = chars[idx];
      System.out.write((char) achar);
      Thread.yield();
     }
    }
   }
  }
 }
}
方法2: 使用信号灯:Semaphore(1)表示只能运行一个程序,Semaphore(n)可以运行n个线程
public class CriticalSectionSemaphore

{

 static String message = "Now Is The Time For All Good Men\n";

 static int numThreads = 200;



 public static void main(String args[])

 {

  for (int idx = 0; idx < numThreads; idx++) {

   Thread t = new Thread(new StreamPrinter());

   t.start();

  }

 }



 static class StreamPrinter implements Runnable

 {

  static Semaphore sema = new Semaphore(1);



  @Override

  public void run()

  {

   try {

    while (true) {

     byte chars[] = message.getBytes();

     sema.acquire();

     for (int idx = 0; idx < chars.length; idx++) {

      byte achar = chars[idx];

      System.out.write((char) achar);

      Thread.yield();

     }

     sema.release();

    }

   }

   catch (InterruptedException ex) {

    System.err.println(ex.getLocalizedMessage());

   }

  }

 }

}
acquire();表示获取信号 release();表示释放信号
1:  public class CriticalSectionMonitor  
2:  {  
3:       static String message = "Now Is The Time For All Good Men\n";  
4:       static int numThreads = 200;  
5:       static Object monitor = new Object();  
6:       public static void main(String args[])  
7:       {  
8:            for (int idx = 0; idx < numThreads; idx++) {  
9:                 Thread t = new Thread(new StreamPrinter());  
10:                 t.start();  
11:            }  
12:            // Needed to start / unblock the first waiting thread.   
13:            synchronized(monitor) {  
14:                 monitor.notify();  
15:            }  
16:       }  
17:       static class StreamPrinter implements Runnable  
18:       {  
19:            @Override  
20:            public void run()  
21:            {  
22:                 try {  
23:                      while (true) {  
24:                           byte chars[] = message.getBytes();  
25:                           synchronized(monitor) { // Start Critical Section  
26:                                monitor.wait();  
27:                           }  
28:                           for (int idx = 0; idx < chars.length; idx++) {  
29:                                byte achar = chars[idx];  
30:                                System.out.write((char) achar);  
31:                                Thread.yield();  
32:                           }  
33:                           synchronized(monitor) { // End Critical Section  
34:                                monitor.notify();  
35:                           }  
36:                      }  
37:                 }  
38:                 catch (InterruptedException ex) {  
39:                      System.err.println(ex.getLocalizedMessage());  
40:                 }  
41:            }  
42:       }  
43:  }  




方法3:monitor


  1. public class CriticalSectionMonitor
  2. {
  3. static String message = "Now Is The Time For All Good Men\n";
  4. static int numThreads = 200;
  5. static Object monitor = new Object();
  6. public static void main(String args[])
  7. {
  8. for (int idx = 0; idx < numThreads; idx++) {
  9. Thread t = new Thread(new StreamPrinter());
  10. t.start();
  11. }
  12. // Needed to start / unblock the first waiting thread.
  13. synchronized(monitor) {
  14. monitor.notify();
  15. }
  16. }
  17. static class StreamPrinter implements Runnable
  18. {
  19. @Override
  20. public void run()
  21. {
  22. try {
  23. while (true) {
  24. byte chars[] = message.getBytes();
  25. synchronized(monitor) { // Start Critical Section
  26. monitor.wait();
  27. }
  28. for (int idx = 0; idx < chars.length; idx++) {
  29. byte achar = chars[idx];
  30. System.out.write((char) achar);
  31. Thread.yield();
  32. }
  33. synchronized(monitor) { // End Critical Section
  34. monitor.notify();
  35. }
  36. }
  37. }
  38. catch (InterruptedException ex) {
  39. System.err.println(ex.getLocalizedMessage());
  40. }
  41. }
  42. }
  43. }


注意下面两个例子中的错误,第一个是是没有同步方法,第二个是同步错误,该class使用同步方法,但是没有静态化,所以200个线程只是锁定了自己的方法,同步没有达到该有的效果。
  1. public class CriticalSectionBroken
  2. {
  3. static String message = "Now Is The Time For All Good Men\n";
  4. static int numThreads = 200;
  5. public static void main(String args[])
  6. {
  7. for (int idx = 0; idx < numThreads; idx++) {
  8. Thread t = new Thread(new StreamPrinter());
  9. t.start();
  10. }
  11. }
  12. static class StreamPrinter implements Runnable
  13. {
  14. @Override
  15. public void run()
  16. {
  17. while (true) {
  18. byte chars[] = message.getBytes();
  19. for (int idx = 0; idx < chars.length; idx++) {
  20. byte achar = chars[idx];
  21. System.out.write((char) achar);
  22. Thread.yield();
  23. }
  24. }
  25. }
  26. }
  27. }
  1. public class CriticalSectionFailedSynchronize
  2. {
  3. static String message = "Now Is The Time For All Good Men\n";
  4. static int numThreads = 200;
  5. public static void main(String args[])
  6. {
  7. for (int idx = 0; idx < numThreads; idx++) {
  8. Thread t = new Thread(new StreamPrinter());
  9. t.start();
  10. }
  11. }
  12. static class StreamPrinter implements Runnable
  13. {
  14. @Override
  15. public void run()
  16. {
  17. while (true) {
  18. printMessage();
  19. }
  20. }
  21. private synchronized void printMessage()
  22. {
  23. byte chars[] = message.getBytes();
  24. for (int idx = 0; idx < chars.length; idx++) {
  25. byte achar = chars[idx];
  26. System.out.write((char) achar);
  27. Thread.yield();
  28. }
  29. }
  30. }
  31. }

Monday, March 9, 2015

java读取excel文件并改变格式输出到txt文件

1. java导入导出Excel文件要引入jxl.jar包,最关键的是这套API是纯Java的,并不依赖Windows系统,即使运行在Linux下,它同样能够正确的处理Excel文件。下载地址:http://www.andykhan.com/jexcelapi/
2. 2.jxl对Excel表格的认识:每个单元格的位置认为是由一个二维坐标(i,j)给定,其中i表示列,j表示行,并且从上到下递增,从左到右递增。
3. 本代码读取text.xls的头三列,按行输出到result.txt
稍微改变格式


  1. import java.io.File;
  2. import java.io.FileOutputStream;

  3. import jxl.*; 




  4. public class Read_excel{
  5.     public static void main(String[] args) {
  6.         int i;
  7.         Sheet sheet;
  8.         Workbook book;
  9.         Cell cell1,cell2,cell3;
  10.         String content;
  11.         try { 
  12.             //t.xls为要读取的excel文件名
  13.             book= Workbook.getWorkbook(new File("e:\\test.xls")); 
  14.             
  15.             //获得第一个工作表对象(ecxel中sheet的编号从0开始,0,1,2,3,....)
  16.             sheet=book.getSheet(0); 
  17.             //获取左上角的单元格
  18.             cell1=sheet.getCell(0,0);
  19.             System.out.println("标题:"+cell1.getContents()); 
  20.             
  21.             File outFile=new File("e:\\result.txt");
  22.             FileOutputStream fos=new FileOutputStream(outFile);
  23.             
  24.             
  25.             i=1;
  26.             while(true)
  27.             {
  28.                 //获取每一行的单元格 
  29.                 cell1=sheet.getCell(0,i);//(列,行)
  30.                 cell2=sheet.getCell(1,i);
  31.                 cell3=sheet.getCell(2,i);
  32.                 if("".equals(cell1.getContents())==true)    //如果读取的数据为空
  33.                     break;       System.out.println(cell1.getContents()+"\t"+cell2.getContents()+"\t"+cell3.getContents());
  34.                 content=cell1.getContents()+"\t"+cell2.getContents()+"0000&&&&&"+cell3.getContents()+"\r\n";
  35.                 byte[] contentInBytes = content.getBytes();
  36.                 fos.write(contentInBytes);
  37.                 i++;
  38.             }
  39.             book.close(); 
  40.             fos.close();
  41.         }
  42.         catch(Exception e)  { } 
  43.     }
  44. }

Sunday, February 8, 2015

ubuntu的一些有用操作

apt-get remove openjdk*  remove openjdk
java安装在哪里了 通过whereis java命令不能知道java真是的安装路径
可以通过 update-alternatives --config java 命令察看

Saturday, September 20, 2014

List和iterator方法

import java.util.*;
class TestArrayList
{
public static void main(String[] args)
{
LinkedList al=new LinkedList();
al.add("java1");
al.add("java2");
al.add(3);
al.add("java4");
al.remove("java4");
sop(al);

Iterator it=al.iterator();//接口型引用指向的是子类对象(集合中的方法获得)
while (it.hasNext())
{
sop(it.next());
}
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}

Friday, September 19, 2014

 interface PetRestaurant
{
    public void buy();
}


 class DogPet implements PetRestaurant
{
    @Override
    public void buy()
    {
        System.out.println("我是狗,我要买狗粮");
    }
}

 class CatPet implements PetRestaurant
{
    @Override
    public void buy()
    {
        System.out.println("我是猫,我要买猫粮");
    }

}

 class test
{
    public void buy(PetRestaurant pet)
    {
        pet.buy();
    }
}


public class Tests
{
    public static void main(String[] args)
    {
        PetRestaurant dog = new DogPet(); //实例化一个狗,相当于把狗顾客实例化
        PetRestaurant cat = new CatPet();//实例化一个猫,相当于把猫顾客实例化
        test t = new test(); //实例化一个店小二
        t.buy(cat); //把猫交给店小二
        t.buy(dog); //把狗交给店小二
    }

}

接口的使用2


1)
public interface Handler{
  public void Hello();
}

2)
import Handler;
public class OtherParser{
  Handler handler;
......
}

接口是永远不能被实例化的,2只是对接口做引用,并没有被实例化。

接口可以看成是高度抽象的抽象类,它描述的事物们所共有的方法(方法签名),也就是规定除了该接口的方法的调用参数与规则,仅仅而已,它的使用必须依赖于实现类。
例如:
 public class MyHandler implements Handler{
  public void Hellp(){
    System.out.println("my Handler implements");
  }  
 }
而在对接口的引用时,采用的是实例化实现该接口的类
Handler handler = new MyHander();

接口在面向对象中是很重要。需要好好理解。

java接口的使用 zz

接口的作用对于很多新手来说很不容易理解,我给大家举个例子。
接口只是一个规范,所以里面的方法都是空的。
假如我开了一个宠物粮店,声明所有宠物都可以来我这里买粮食,这就相当于一个接口,

public interface PetRestaurant {
public void buy();
}

当一只狗看到了,知道自己是宠物,所以它去实现这个接口
public class DogPet implements PetRestaurant {
@Override
public void buy() {
System.out.println("我是狗,我要买狗粮");
}
}
当一只猫看到了,知道自己也是宠物,所以也去实现这个接口
public class CatPet implements PetRestaurant {
@Override
public void buy() {
System.out.println("我是猫,我要买猫粮");
}

}
当狗和猫来我的店之前,我是不知道他们到底是什么,但是当他们来到我的店,我就知道一个要猫粮食,一个要狗粮食。因为他们都实现了 我这个接口,都可以买。下面这个类相当于一个接待顾客的类,即店小二,他接待所有实现了我这个宠物店接口的动物,传进来一个PetRestaurant 类型的宠物,注意,这个PetRestaurant 是接口
public class test {
public void buy(PetRestaurant pet)
{
pet.buy();
}
}

好了,这个时候我这个老板出现了,我可以给他们卖粮食了,相当于测试类
public class Tests {
public static void main(String[] args) {
PetRestaurant dog = new DogPet(); //实例化一个狗,相当于把狗顾客实例化
PetRestaurant cat = new CatPet();//实例化一个猫,相当于把猫顾客实例化

test t = new test(); //实例化一个店小二
t.buy(cat); //把猫交给店小二
t.buy(dog); //把狗交给店小二
}

}
这样运行的结果就是
我是猫,我要买猫粮
我是狗,我要买狗娘

你知道吗,整个过程我这个店主其实根本不知道来的到底是猫是狗还是其他什么,我只要有一个店小二,把这些来的不知什么动物都全部交给店小二,店小二就知道怎么去卖了,因为这些狗啊猫啊都实现了我这个宠物店的接口,而店小二就负责接待所有实现了我这个接口的动物。这就有一个好处,假如明天来了一头小猪,只要它实现了我这个接口,我只管交给店小二处理就OK了,我这个店小二根本不需要变化,我这个店主也只需要实例化一下这个动物就OK
你想,假如没有接口,会怎么办,来一个猫,我要去创造一个猫,还要实例化,来一只狗,我要创建一只狗,同样要实例化,还要配备专门的店小二去接待,就会相当麻烦