且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java小知识点-1

更新时间:2022-10-10 23:19:32

【注】windows设置环境变量,例如设置jdk为1.7.0版本(一定要把%path%加上):
set path="D:\ProgramFiles\Java\jdk1.7.0\bin";%path%
1、截取字符串:
String currentURI = req.getRequestURI();//test_servlet/user/addUser.do
    System.out.println("currentURI=" + currentURI);    
    String path = currentURI.substring(currentURI.indexOf("/", 1));    
    path = path.substring(0, path.indexOf("."));    
    System.out.println("path=" + path);
struts的RequestProcessor类中对URL字符串的处理函数
protected String processPath(HttpServletRequest request,
                HttpServletResponse response)
                throws IOException {
                String path;

                // Set per request the original path for postback forms
                if (request.getAttribute(Globals.ORIGINAL_URI_KEY) == null) {
                        request.setAttribute(Globals.ORIGINAL_URI_KEY, request.getServletPath());
                }

                // For prefix matching, match on the path info (if any)
                path = (String) request.getAttribute(INCLUDE_PATH_INFO);

                if (path == null) {
                        path = request.getPathInfo();
                }

                if ((path != null) && (path.length() > 0)) {
                        return (path);
                }

                // For extension matching, strip the module prefix and extension
                path = (String) request.getAttribute(INCLUDE_SERVLET_PATH);

                if (path == null) {
                        path = request.getServletPath();
                }

                String prefix = moduleConfig.getPrefix();

                if (!path.startsWith(prefix)) {
                        String msg = getInternal().getMessage("processPath");
                        log.error(msg + " " + request.getRequestURI());
                        response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);

                        return null;
                }

                path = path.substring(prefix.length());

                int slash = path.lastIndexOf("/");
                int period = path.lastIndexOf(".");

                if ((period >= 0) && (period > slash)) {
                        path = path.substring(0, period);
                }

                return (path);
        }

2 列出目录下的所有文件

public static void main(String args[])
  {
    loop("d:\\") ;
  }
  public static void loop(String dir)
  {
    File f = new File(dir) ;
    String str[] = null ;
    if(f.isDirectory())
    {
      str = f.list() ;
      for(int i=0;i<str.length;i++)
      {
        loop(dir+"\\"+str[i]) ;
      }
    }
    else
    {
      System.out.println(dir) ;
    }
    
  }

3 随机读取文件, RandomAccessFile类

  // 随机读取
    RandomAccessFile raf1 = new RandomAccessFile("f:\\demo.txt","rw") ;
    // 随机读取有一个限制,就是说如果要进行操作,则必须指定好数据的存储长度
    // 保存姓名(8位字符串)和年龄(int 4):
    String name = "zhangsan" ;
    int age = 20 ;
    raf1.write(name.getBytes()) ;
    raf1.writeInt(age) ;
    

    name = "lisi        " ;
    age = 30 ;
    raf1.write(name.getBytes()) ;
    raf1.writeInt(age) ;

    name = "wangwu     " ;
    age = 33 ;
    raf1.write(name.getBytes()) ;
    raf1.writeInt(age) ;

    raf1.close() ;

    RandomAccessFile raf2 = new RandomAccessFile("f:\\demo.txt","r") ;
    // 读取第二个人的数据
    raf2.skipBytes(12) ;
    byte b[] = new byte[8] ;
    raf2.read(b) ;
    int age2 = raf2.readInt() ;
    System.out.println(new String(b)+" --> "+age2) ;

4 文件读写

写入文件
// 1、表示要操作lxh.txt文件
    File f = new File("f:\\lxh.txt") ;
    OutputStream out = null ;
    // 2、通过子类实例化
    // 使用FileOutputStream子类
    try
    {
      out = new FileOutputStream(f) ;
    }
    catch (Exception e)
    {
    }
    // 将字符串转化为byte数组
    String str = "HELLO MLDN ..." ;
    byte b[] = str.getBytes() ;
    // 3、将byte数组写入到文件之中,写的是byte数组中的内容
    try
    {
      out.write(b) ;
    }
    catch (Exception e)
    {
    }
读取文件
File f = new File("f:\\lxh.txt") ;
    InputStream in = null ;
    try
    {
      in = new FileInputStream(f) ;
    }
    catch (Exception e)
    {
    }
    // 声明一个byte数组,用于接收内容
    byte b[] = new byte[500] ;
    int len = 0 ;
    try
    {
      // 所有的数据都在byte数组中
      len = in.read(b) ;
    }
    catch (Exception e)
    {
    }
    try
    {
      in.close() ;
    }
    catch (Exception e)
    {
    }
    System.out.println(new String(b,0,len)) ;
    // 输出打印的内容

【注意】读取文件为流文件可用用new FileInputStream("product.xml"), 而不用new FileInputStream(new File("product.xml"), 文件必须放在classpath下面才能找到

 

 

5、Java的国际化与本地化

在Java的uitl包下面,存在着本地化的包Local, 同时在java的bin目录下面提供了命令用于批量的将本地化语言(比如中文)转化为utf-8的命令:native2ascii, 使用方法为:native2ascii.ext a.properties MessageBundle_zh_CN.properties, 同时也可以双击native2ascii.ext将单独的某些中文词汇转化为utf-8.
 
Locale defaultLocale = Locale.getDefault();
    System.out.println("default country=" + defaultLocale.getCountry());
    System.out.println("default language=" + defaultLocale.getLanguage());
    
    //Locale currentLocale = new Locale("en", "US");
    //Locale currentLocale = new Locale("zh", "CN");
    
    Locale currentLocale = new Locale("ja""JP");
    
    ResourceBundle rb = ResourceBundle.getBundle("res.MessagesBundle", currentLocale);
    //System.out.println(rb.getString("k1"));
    //System.out.println(rb.getString("k2"));
    
    MessageFormat mf = new MessageFormat(rb.getString("k1"));
    System.out.println(mf.format(new Object[]{"Tom"}));
    //System.out.println(mf.format(new Object[]{"张三"}));

 


  1. Locale defaultLocale = Locale.getDefault(); 
  2.         //Locale defaultLocale = new Locale("en","US"); 
  3.          
  4.         ResourceBundle rb = ResourceBundle.getBundle("res/MessagesBundle", defaultLocale); 
  5.         //ResourceBundle rb = ResourceBundle.getBundle("res.MessagesBundle", defaultLocale); 
  6.         System.out.println(rb.getString("msg0")); 

 【注】ResourceBundle.getBundle("res/MessagesBundle", defaultLocale);

ResourceBundle.getBundle("res.MessagesBundle", defaultLocale); 其中'/','.'表达了同样的

含义,即在src/main/java下面存在res的子文件夹(在Eclipse中是folder,不是source folder),下面存

在着MessagesBundle为前缀的Properties文件,例如:MessagesBundle_en_US.properties、MessagesBundle_zh_CN.properties。

  关键在于ResourceBundle.getBundle(“message“)。显然这个message与那两个message*.properties文件大有关系。查阅一下JDK的文档可以发现,ResourceBundle实际上是把“message“当作一个basename使用,然后根据当前的Locale和国家来查找basename_*.properties文件,所以当Local分别为中文和英文时,ResourceBundle分别使用的就是message_zh.properties和message_en.properties文件。然后ResourceBundle读入找到的.properties文件,并对其中的资源进行处理,这就不难理解ResourceBundle.getString(“msg0“)的结果了(msg0=“** locale“)。
  为了求证以上的分析,我又查看了一下java的源代码,getBundle实际上会转而调用getBundleImpl,getBundleImpl先确定实际使用的Locale,然后根据搜索规则形成一个搜索列表,再交给findBundle处理,然后由findBundle完成实际.properties文件的搜索工作。所有代码均在JDK的java.util.ResourceBundle.java中,不再列举。
  Eclipse的国际化和本地化的实现,实际上就是基于ResourceBundle来实现的

6、压制串行化警告:@SupressWarnings("serial")

If your class implements the interface java.io.Serializeable, either directly or indirectly, you should provide a field called serialVersionUID. If you do not provide this field and compile the class, you will get a warning at compile time. If you do not want this warning, simply add the line @SupressWarnings("serial") before your class definition.
 

7、首字母大写

public static void main(String[] args) {
    String str = "zhang";
    str = str.substring(0,1).toUpperCase()+str.substring(1);
    System.out.println(str);
    }

8、取得类名称

取得类的全路径名:com.company.Person
object.getClass().getName()
取得类的简单名称:Person
object.getClass().getSimpleName()

9、将java.sql.Date转换为需要的格式
格式转换
import java.sql.Date;
import java.text.SimpleDateFormat;

public class DateUtils {
  
public static void main(String[] args) {
    SimpleDateFormat sdf = 
new SimpleDateFormat("yyyy年MM月dd日");
    System.out.println(
new Date(1000000000));
    System.out.println(sdf.format(
new Date(1000000000)));
  }
}
执行结果:
1970-01-12
1970年01月12日
 
取得精确的时分秒
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class DateUtils {
  public static void main(String[] args) {
    Date date = new Date(1000000000);
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    System.out.println(sdf.format(date));
  }
}
执行结果:21:46:40
 
取得年月日
import java.sql.Date;
import java.util.Calendar;

public class DateUtils {
  public static void main(String[] args) {
    Date date = new Date(1000000000);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    System.out.println(date);
    System.out.println(calendar.get(Calendar.YEAR));
    System.out.println(calendar.get(Calendar.MONTH));
    System.out.println(calendar.get(Calendar.DATE));
  }
}
执行结果:
1970-01-12
1970
12
 
取得毫秒数(HH:24小时制,hh:12小时制):yyyy-MM-dd HH:mm:ss S
区别:oracle可以使用:hh24区分24小时制还是12小时制

10、判断一组逻辑返回结果是否都为true或者false的问题


  1. boolean[] flags = { truetruetruetruefalse }; 
  2.         boolean result = true
  3.         for (int i = 0; i < flags.length; i++) { 
  4.             result &= flags[i]; 
  5.         } 
  6.         System.out.println(result); 
 
11、当前文件的绝对地址
new File("HelloWorld.java").getAbsolutePath();
 

 12、比较两个日期相差的天数


  1. (版本1) 
  2. public static int getIntervalDays(Date fDate, Date oDate) { 
  3.        if (null == fDate || null == oDate) { 
  4.            return -1
  5.        } 
  6.        long intervalMilli = oDate.getTime() – fDate.getTime(); 
  7.        return (int) (intervalMilli / (24 * 60 * 60 * 1000)); 
  8.     } 
  9.   
  10.     (版本2) 
  11. public static int daysOfTwo(Date fDate, Date oDate) { 
  12.        Calendar aCalendar = Calendar.getInstance(); 
  13.        aCalendar.setTime(fDate); 
  14.        int day1 = aCalendar.get(Calendar.DAY_OF_YEAR); 
  15.        aCalendar.setTime(oDate); 
  16.        int day2 = aCalendar.get(Calendar.DAY_OF_YEAR); 
  17.        return day2 – day1; 
  18.     } 

 13、内部类的实例化

原则:先实例化外面的类,再实例化里面的类。 具体示例如下:

  1. class aa{ 
  2.  class kk{ 
  3.  class gg{ 
  4.  int tt=100
  5.  public void a(){ 
  6.  System.out.println("a"); 
  7.  } 
  8.  } 
  9.   
  10.  }  
  11.  public static void main(String[] args){ 
  12.    
  13.   kk k = new aa().new kk(); 
  14.   kk.gg g = new aa().new kk().new gg(); 
  15.  } 
  16. }  

 14、对象的克隆:实现Cloneable接口


  1. class Person implements Cloneable{  // 实现Cloneable接口表示可以被克隆  
  2.     private String name ; 
  3.     public Person(String name){ 
  4.         this.name = name ; 
  5.     } 
  6.     public void setName(String name){ 
  7.         this.name = name ; 
  8.     } 
  9.     public String getName(){ 
  10.         return this.name ; 
  11.     } 
  12.     public String toString(){ 
  13.         return "姓名:" + this.name ; 
  14.     } 
  15.     public Object clone() 
  16.                 throws CloneNotSupportedException 
  17.     { 
  18.         return super.clone() ;  // 具体的克隆操作由父类完成 
  19.     } 
  20. }; 
  21. public class CloneDemo01{ 
  22.     public static void main(String args[]) throws Exception{ 
  23.         Person p1 = new Person("张三") ; 
  24.         Person p2 = (Person)p1.clone() ; 
  25.         p2.setName("李四") ; 
  26.         System.out.println("原始对象:" + p1) ; 
  27.         System.out.println("克隆之后的对象:" + p2) ; 
  28.     } 
  29. }; 

 15、数组的排序和查找


  1. import java.util.* ; 
  2. public class ArraysDemo{ 
  3.     public static void main(String arg[]){ 
  4.         int temp[] = {3,4,5,7,9,1,2,6,8} ;  // 声明一个整型数组 
  5.         Arrays.sort(temp) ;     // 进行排序的操作 
  6.         System.out.print("排序后的数组:") ; 
  7.         System.out.println(Arrays.toString(temp)) ; // 以字符串输出数组 
  8.         // 如果要想使用二分法查询的话,则必须是排序之后的数组 
  9.         int point = Arrays.binarySearch(temp,3) ;   // 检索位置 
  10.         System.out.println("元素‘3’的位置在:" + point) ; 
  11.         Arrays.fill(temp,3) ;// 填充数组 
  12.         System.out.print("数组填充:") ; 
  13.         System.out.println(Arrays.toString(temp)) ; 
  14.     } 
  15. }; 

 16、观察者设计模式:Observable、Observer


  1. import java.util.* ; 
  2. class House extends Observable{ // 表示房子可以被观察 
  3.     private float price ;// 价钱 
  4.     public House(float price){ 
  5.         this.price = price ; 
  6.     } 
  7.     public float getPrice(){ 
  8.         return this.price ; 
  9.     } 
  10.     public void setPrice(float price){ 
  11.         // 每一次修改的时候都应该引起观察者的注意 
  12.         super.setChanged() ;    // 设置变化点 
  13.         super.notifyObservers(price) ;// 价格被改变 
  14.         this.price = price ; 
  15.     } 
  16.     public String toString(){ 
  17.         return "房子价格为:" + this.price ; 
  18.     } 
  19. };  
  20. class HousePriceObserver implements Observer{ 
  21.     private String name ; 
  22.     public HousePriceObserver(String name){ // 设置每一个购房者的名字 
  23.         this.name = name ; 
  24.     } 
  25.     public void update(Observable o,Object arg){ 
  26.         if(arg instanceof Float){ 
  27.             System.out.print(this.name + "观察到价格更改为:") ; 
  28.             System.out.println(((Float)arg).floatValue()) ; 
  29.         } 
  30.     } 
  31. }; 
  32. public class ObserDemo01{ 
  33.     public static void main(String args[]){ 
  34.         House h = new House(1000000) ; 
  35.         HousePriceObserver hpo1 = new HousePriceObserver("购房者A") ; 
  36.         HousePriceObserver hpo2 = new HousePriceObserver("购房者B") ; 
  37.         HousePriceObserver hpo3 = new HousePriceObserver("购房者C") ; 
  38.         h.addObserver(hpo1) ; 
  39.         h.addObserver(hpo2) ; 
  40.         h.addObserver(hpo3) ; 
  41.         System.out.println(h) ; // 输出房子价格 
  42.         h.setPrice(666666) ;    // 修改房子价格 
  43.         System.out.println(h) ; // 输出房子价格 
  44.     } 
  45. }; 

 

 17、任务的定时执行:扩展于TimerTask类、使用Timer类进行调度


  1. // 完成具体的任务操作  
  2. import java.util.TimerTask ; 
  3. import java.util.Date ; 
  4. import java.text.SimpleDateFormat ; 
  5. class MyTask extends TimerTask{ // 任务调度类都要继承TimerTask 
  6.     public void run(){ 
  7.         SimpleDateFormat sdf = null ; 
  8.         sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS") ; 
  9.         System.out.println("当前系统时间为:" + sdf.format(new Date())) ; 
  10.     } 
  11. }; 
  12. import java.util.Timer ; 
  13. public class TestTask{ 
  14.     public static void main(String args[]){ 
  15.         Timer t = new Timer() ; // 建立Timer类对象 
  16.         MyTask mytask = new MyTask() ;  // 定义任务 
  17.         t.schedule(mytask,1000,2000) ;  // 设置任务的执行,1秒后开始,每2秒重复 
  18.     } 
  19. }; 
 
 
【注意】
1、运算符的优先级
运算符优先级表
优先级
运算符
结合性
1
() [] .
从左到右
2
! +(正)  -(负) ~ ++ --
从右向左
3
* / %
从左向右
4
+(加) -(减)
从左向右
5
<< >> >>>
从左向右
6
< <= > >= instanceof
从左向右
7
==   !=
从左向右
8
&(按位与)
从左向右
9
^
从左向右
10
|
从左向右
11
&&
从左向右
12
||
从左向右
13
?:
从右向左
14
= += -= *= /= %= &= |= ^=  ~=  <<= >>=   >>>=
从右向左
 
注意‘+’优先于‘instanceof’。 
 
18、手工编译和运行样例,避免遗忘
Hello.java

  1. package com.alibaba.demo; 
  2. public class Hello{ 
  3.     public static void main(String[] args){ 
  4.         System.out.println("hello"); 
  5.     } 
编译:javac -d . Hello.java
在当前目录下执行(使用'.'或者'/'均可):
java com.alibaba.demo.Hello 或者 
java com/alibaba/demo/Hello
 
 
 本文转自 tianya23 51CTO博客,原文链接:http://blog.51cto.com/tianya23/305251,如需转载请自行联系原作者