java小知识点_Java小知识点-1

Java小知识点-1

【注】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

{

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[]{"张三"}));

Locale defaultLocale = Locale.getDefault();

//Locale defaultLocale = new Locale("en","US");

ResourceBundle rb = ResourceBundle.getBundle("res/MessagesBundle", defaultLocale);

//ResourceBundle rb = ResourceBundle.getBundle("res.MessagesBundle", defaultLocale);

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转换为需要的格式

格式转换

importjava.sql.Date;importjava.text.SimpleDateFormat;publicclassDateUtils {publicstaticvoidmain(String[] args) {

SimpleDateFormat sdf =newSimpleDateFormat("yyyy年MM月dd日");

System.out.println(newDate(1000000000));

System.out.println(sdf.format(newDate(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

0

12

取得毫秒数(HH:24小时制,hh:12小时制):yyyy-MM-dd HH:mm:ss S

区别:oracle可以使用:hh24区分24小时制还是12小时制

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

boolean[] flags = {true,true,true,true,false};

booleanresult =true;

for(inti =0; i 

result &= flags[i];

}

System.out.println(result);

11、当前文件的绝对地址

new File("HelloWorld.java").getAbsolutePath();

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

(版本1)

publicstaticintgetIntervalDays(Date fDate, Date oDate) {

if(null== fDate ||null== oDate) {

return-1;

}

longintervalMilli = oDate.getTime() – fDate.getTime();

return(int) (intervalMilli / (24*60*60*1000));

}

(版本2)

publicstaticintdaysOfTwo(Date fDate, Date oDate) {

Calendar aCalendar = Calendar.getInstance();

aCalendar.setTime(fDate);

intday1 = aCalendar.get(Calendar.DAY_OF_YEAR);

aCalendar.setTime(oDate);

intday2 = aCalendar.get(Calendar.DAY_OF_YEAR);

returnday2 – day1;

}

13、内部类的实例化

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

class aa{

class kk{

class gg{

int tt=100;

public void a(){

System.out.println("a");

}

}

}

public static void main(String[] args){

kk k = new aa().new kk();

kk.gg g = new aa().new kk().new gg();

}

}

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

classPersonimplementsCloneable{// 实现Cloneable接口表示可以被克隆

privateString name ;

publicPerson(String name){

this.name = name ;

}

publicvoidsetName(String name){

this.name = name ;

}

publicString getName(){

returnthis.name ;

}

publicString toString(){

return"姓名:"+this.name ;

}

publicObject clone()

throwsCloneNotSupportedException

{

returnsuper.clone() ;// 具体的克隆操作由父类完成

}

};

publicclassCloneDemo01{

publicstaticvoidmain(String args[])throwsException{

Person p1 = newPerson("张三") ;

Person p2 = (Person)p1.clone() ;

p2.setName("李四") ;

System.out.println("原始对象:"+ p1) ;

System.out.println("克隆之后的对象:"+ p2) ;

}

};

15、数组的排序和查找

importjava.util.* ;

publicclassArraysDemo{

publicstaticvoidmain(String arg[]){

inttemp[] = {3,4,5,7,9,1,2,6,8} ;// 声明一个整型数组

Arrays.sort(temp) ;     // 进行排序的操作

System.out.print("排序后的数组:") ;

System.out.println(Arrays.toString(temp)) ; // 以字符串输出数组

// 如果要想使用二分法查询的话,则必须是排序之后的数组

intpoint = Arrays.binarySearch(temp,3) ;// 检索位置

System.out.println("元素‘3’的位置在:"+ point) ;

Arrays.fill(temp,3) ;// 填充数组

System.out.print("数组填充:") ;

System.out.println(Arrays.toString(temp)) ;

}

};

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

importjava.util.* ;

classHouseextendsObservable{// 表示房子可以被观察

privatefloatprice ;// 价钱

publicHouse(floatprice){

this.price = price ;

}

publicfloatgetPrice(){

returnthis.price ;

}

publicvoidsetPrice(floatprice){

// 每一次修改的时候都应该引起观察者的注意

super.setChanged() ;// 设置变化点

super.notifyObservers(price) ;// 价格被改变

this.price = price ;

}

publicString toString(){

return"房子价格为:"+this.price ;

}

};

classHousePriceObserverimplementsObserver{

privateString name ;

publicHousePriceObserver(String name){// 设置每一个购房者的名字

this.name = name ;

}

publicvoidupdate(Observable o,Object arg){

if(arginstanceofFloat){

System.out.print(this.name +"观察到价格更改为:") ;

System.out.println(((Float)arg).floatValue()) ;

}

}

};

publicclassObserDemo01{

publicstaticvoidmain(String args[]){

House h = newHouse(1000000) ;

HousePriceObserver hpo1 = newHousePriceObserver("购房者A") ;

HousePriceObserver hpo2 = newHousePriceObserver("购房者B") ;

HousePriceObserver hpo3 = newHousePriceObserver("购房者C") ;

h.addObserver(hpo1) ;

h.addObserver(hpo2) ;

h.addObserver(hpo3) ;

System.out.println(h) ; // 输出房子价格

h.setPrice(666666) ;// 修改房子价格

System.out.println(h) ; // 输出房子价格

}

};

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

// 完成具体的任务操作

importjava.util.TimerTask ;

importjava.util.Date ;

importjava.text.SimpleDateFormat ;

classMyTaskextendsTimerTask{// 任务调度类都要继承TimerTask

publicvoidrun(){

SimpleDateFormat sdf = null;

sdf = newSimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS") ;

System.out.println("当前系统时间为:"+ sdf.format(newDate())) ;

}

};

importjava.util.Timer ;

publicclassTestTask{

publicstaticvoidmain(String args[]){

Timer t = newTimer() ;// 建立Timer类对象

MyTask mytask = newMyTask() ;// 定义任务

t.schedule(mytask,1000,2000) ;// 设置任务的执行,1秒后开始,每2秒重复

}

};

【注意】

1、运算符的优先级

运算符优先级表

优先级

运算符

结合性

1

() [] .

从左到右

2

! +(正)  -(负) ~ ++ --

从右向左

3

* / %

从左向右

4

+(加) -(减)

从左向右

5

<> >>>

从左向右

6

 >= instanceof

从左向右

7

==!=

从左向右

8

&(按位与)

从左向右

9

^

从左向右

10

|

从左向右

11

&&

从左向右

12

||

从左向右

13

?:

从右向左

14

= += -= *= /= %= &= |= ^=  ~=  <<= >>=>>>=

从右向左

注意‘+’优先于‘instanceof’。

18、手工编译和运行样例,避免遗忘

Hello.java

packagecom.alibaba.demo;

publicclassHello{

publicstaticvoidmain(String[] args){

System.out.println("hello");

}

}

编译:javac -d . Hello.java

在当前目录下执行(使用'.'或者'/'均可):

java com.alibaba.demo.Hello 或者

java com/alibaba/demo/Hello

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值