java段级_java非常有用的代码段

1. 获取环境变量

System.getenv("PATH");

System.getenv("JAVA_HOME");

2.获取系统属性

System.getProperty("pencil color"); //得到属性值

java-Dpencil color=green

System.getProperty("java.specifi.cation.version"); //得到Java版本号

Properties p= Systemget.Properties(); //得到所有属性值

p.list(System.out);

3、类型转换

//数字与对象之间互相转换 - Integer转int

Integer.intValue();//浮点数的舍入

Math.round()//数字格式化

Number.Format//整数 -> 二进制字符串

toBinaryString() 或valueOf()//整数 -> 八进制字符串

toOctalString()//整数 -> 十六进制字符串

toHexString()//数字格式化为罗马数字

RomanNumber.Format()//随机数

Random r= newRandom();

r.nextDouble();

r.nextInt();

4. 日期和时间

//查看当前日期

Date today= newDate();

Calendar.getInstance().getTime();//格式化默认区域日期输出

DateFormat df=DateFormat.getInstance();

df.format(today);//格式化制定区域日期输出

DateFormat df_cn=DateFormat.getDateInstance(DateFormat.FULL, Locale.CHINA);

String now=df_cn.format(today);//按要求格式打印日期

SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

sdf.format(today);//设置具体日期

GregorianCalendar d1= new GregorianCalendar(2009, 05, 06); //6月6日

GregorianCalendar d2= new GregorianCalendar(); //今天

Calendar d3= Calendar.getInstance(); //今天

d1.getTime();//Calendar或GregorianCalendar转成Date格式

d3.set(Calendar.YEAR,1999);

d3.set(Calendar.MONTH, Calendar.APRIL);

d3.set(Calendar.DAY_OF_MONTH,12);//字符串转日期

SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

Date now=sdf.parse(String);//日期加减

Date now= newDate();long t =now.getTime();

t+= 700*24*60*60*1000;

Date then= newDate(t);

Calendar now=Calendar.getInstance();

now.add(Calendar.YEAR,-2);//计算日期间隔(转换成long来计算)

today.getTime()-old.getTime();//比较日期

Date 类型,就使用equals(), before(), after()来计算

long类型,就使用==, 来计算//第几日

使用 Calendar的get()方法

Calendar c=Calendar.getInstance();

c.get(Calendar.YEAR);//记录耗时

long start =System.currentTimeMillis();long end =System.currentTimeMillis();long elapsed = end -start;

System.nanoTime();//毫秒//长整形转换成秒

Double.toString(t/1000D);

5. 结构化数据

//数组拷贝

System.arrayCopy(oldArray,0, newArray, 0, oldArray.length);//ArrayList

add(Object o)//在末尾添加给定元素

add(int i, Object o) //在指定位置插入给定元素

clear()//从集合中删除全部元素

Contains(Object o)//如果Vector包含给定元素,返回真值

get(int i) //返回 指定位置的对象句柄

indexOf(Object o)//如果找到给定对象,则返回其索引值;否则,返回-1

remove(Object o)//根据引用删除对象

remove(int i) //根据 位置删除对象

toArray()//返回包含集合对象的数组//Iterator

List list= newArrayList();

Iterator it=list.iterator();while(it.hasNext())

Object o=it.next();//链表

LinkedList list= newLinkedList();

ListIterator it=list.listIterator();while(it.hasNext())

Object o=it.next();//HashMap

HashMap hm = new HashMap();

hmget(key);//通过key得到value

hmput("No1", "Hexinyu");

hmput("No2", "Sean");//方法1: 获取全部键值

Iterator it =hm.values().iterator();while(it.hasNext()) {

String myKey=it.next();

String myValue=hm.get(myKey);

}//方法2: 获取全部键值

for(String key : hm.keySet()) {

String myKey=key;

String myValue=hm.get(myKey);

}//Preferences - 与系统相关的用户设置,类似名-值对

Preferences prefs=PreferencesuserNodeForPackage(ArrayDemo.class);

String text= prefs.get("textFontName", "lucida-bright");

String display= prefs.get("displayFontName", "lucida-balckletter");

System.out.println(text);

System.out.println(display);//用户设置了新值,存储回去

prefs.put("textFontName", "new-bright");

prefs.put("displayFontName", "new-balckletter");//Properties - 类似名-值对,key和value之间,可以用"=",":"或空格分隔,用"#" 和"!"注释

InputStream in= MediationServerclass.getClassLoader().getResourceAsStream("msconfigproperties");

Properties prop= newProperties();

prop.load(in);

in.close();

prop.setProperty(key, value);

prop.getProperty(key);//排序

1数组:Arrays.sort(strings);2List:Collectionssort(list);3 自定义类:class SubComp implementsComparator

然 后使用Arrays.sort(strings,newSubComp())//两个接口

1java.lang.Comparable: 提供对象的自然排序,内置于类中intcompareTo(Object o);booleanequals(Object o2);2java.util.Comparator: 提供特定的比较方法intcompare(Object o1, Object o2)//避免重复排序,可以使用TreeMap

TreeMap sorted= newTreeMap(unsortedHashMap);//排除重复元素

Hashset hs- newHashSet();//搜索对象

binarySearch(): 快 速查询-Arrays, Collections

contains(): 线型搜 索-ArrayList, HashSet, Hashtable, linkedList, Properties, Vector

containsKey(): 检 查集合对象是否包含给定-HashMap, Hashtable, Properties, TreeMap

containsValue(): 主 键(或给定值)-HashMap, Hashtable, Properties, TreeMap

indexOf(): 若 找到给定对象,返回其位置-ArrayList, linkedList, List, Stack, Vector

search(): 线 型搜素-Stack//集合转数组

toArray();//集合总结

Collection: Set-HashSet, TreeSet

Collection: List-ArrayList, Vector, LinkedList

Map: HashMap, HashTable, TreeMap

6.泛型与foreach

//泛型

List myList = new ArrayList();//foreach

for(String s : myList) {

System.out.println(s);

}

7.面向对象

//toString()格式化

public classToStringWith {intx, y;public ToStringWith(int anX, intaY) {

x=anX;

y=aY;

}publicString toString() {return "ToStringWith[" + x + "," + y + "]";

}public static voidmain(String[] args) {

System.out.println(new ToStringWith(43, 78));

}

}//覆盖equals方法

public booleanequals(Object o) {if (o == this) //优化

return true;if (!(o instanceof EqualsDemo)) //可投射到这个类

return false;

EqualsDemo other= (EqualsDemo)o; //类型转换

if (int1 != otherint1) //按字段比较

return false;if (!obj1equals(otherobj1))return false;return true;

}//覆盖hashcode方法

private volatile int hashCode = 0; //延迟初始化

public inthashCode() {if (hashCode == 0) {int result = 17;

result= 37 * result +areaCode;

}returnhashCode;

}//Clone方法

// 要 克隆对象,必须先做两步:1 覆盖对象的clone()方法; 2实现空的Cloneable接口public class Clone1 implementsCloneable {publicObject clone() {returnsuper.clone();

}

}//Finalize方法

Object f= newObject() {public voidfinalize() {

System.out.println("Running finalize()");

}

};

Runtime.getRuntime()addShutdownHook(newThread() {public voidrun() {

System.out.println("Running Shutdown Hook");

}

});

在 调用System.exit(0);的时候,这两个方法将被执行//Singleton模式//实现1

public classMySingleton() {public static final MySingleton INSTANCE = newMySingleton();privateMySingleton() {}

}//实现2

public classMySingleton() {public static MySingleton instance = newMySingleton();privateMySingleton() {}public staticMySingleton getInstance() {returninstance;

}

}//自定义异常

Exception: 编 译时检查

RuntimeException: 运行时检查public class MyException extendsRuntimeException {publicMyException() {super();

}publicMyException(String msg) {super(msg);

}

}

8.输入和输出

//Stream, Reader, Writer

Stream: 处 理字节流

Reader/Writer: 处理字符,通用Unicode//从标准输入设备读数据

1用System.in的BufferedInputStream()读取字节int b =System.in.read();

System.out.println("Read data: " + (char)b); //强 制转换为字符

2BufferedReader 读取文本

如果从Stream转成Reader,使用 InputStreamReader类

BufferedReader is= new BufferedReader(newInputStreamReader(Systemin));

String inputLine;while ((inputLine = is.readLine()) != null) {

System.out.println(inputLine);int val = Integer.parseInt(inputLine); //如果inputLine为整数

}

isclose();//向标准输出设备写数据

1用System.out的println()打印数据2用PrintWriter打印

PrintWriter pw= newPrintWriter(Systemout);

pw.println("The answer is " + myAnswer + " at this time");//Formatter类

格 式化打印内容

Formatter fmtr= newFormatter();

fmtr.format("%1$04d - the year of %2$f", 1951, MathPI);

或 者System.out.printf();或者System.out.format();//原始扫描

voiddoFile(Reader is) {intc;while ((c = is.read()) != -1) {

System.out.println((char)c);

}

}//Scanner扫描

Scanner 可以读取File, InputStream, String, Readabletry{

Scanner scan= new Scanner(new File("atxt"));while(scan.hasNext()) {

String s=scan.next();

}

}catch(FileNotFoundException e) {

e.printStackTrace();

}

}//读取文件

BufferedReader is= new BufferedReader(new FileReader("myFiletxt"));

BufferedOutputStream bos= new BufferedOutputStream(new FileOutputStream("bytesbat"));

is.close();

bo.sclose();//复制文件

BufferedIutputStream is= new BufferedIutputStream(new FileIutputStream("oldFiletxt"));

BufferedOutputStream os= new BufferedOutputStream(new FileOutputStream("newFiletxt"));intb;while ((b = is.read()) != -1) {

os.write(b);

}

is.close();

os.close();//文件读入字符串

StringBuffer sb= newStringBuffer();char[] b = new char[8192];intn;//读一个块,如果有字符,加入缓冲区

while ((n = is.read(b)) > 0) {

sb.append(b,0, n);

}returnsb.toString();//重定向标准流

String logfile= "errorlog";

System.setErr(new PrintStream(newFileOutputStream(logfile)));//读写不同字符集文本

BufferedReader chinese= new BufferedReader(new InputStreamReader(new FileInputStream("chinesetxt"), "ISO8859_1"));

PrintWriter standard= new PrintWriter(new OutputStreamWriter(new FileOutputStream("standardtxt"), "UTF-8"));//读取二进制数据

DataOutputStream os= new DataOutputStream(new FileOutputStream("atxt"));

os.writeInt(i);

os.writeDouble(d);

os.close();//从指定位置读数据

RandomAccessFile raf= new RandomAccessFile(fileName, "r"); //r表示已 只读打开

raf.seek(15); //从15开始读

raf.readInt();

raf.radLine();//串行化对象

对象串 行化,必须实现Serializable接口//保存 数据到磁盘

ObjectOutputStream os= new ObjectOutputStream(new BufferedOutputStream(newFileOutputStream(FILENAME)));

os.writeObject(serialObject);

os.close();//读出数据

ObjectInputStream is= new ObjectInputStream(newFileInputStream(FILENAME));

is.readObject();

isclose();//读写Jar或Zip文档

ZipFile zippy= new ZipFile("ajar");

Enumeration all= zippyentries(); //枚举值列出所有文件清单

while(all.hasMoreElements()) {

ZipEntry entry=(ZipEntry)allnextElement();if(entry.isFile())

println("Directory: " +entry.getName());//读写文件

FileOutputStream os= newFileOutputStream(entry.getName());

InputStream is=zippygetInputStream(entry);int n = 0;byte[] b = new byte[8092];while ((n = is.read(b)) > 0) {

os.write(b,0, n);

is.close();

os.close();

}

}//读写gzip文档

FileInputStream fin= newFileInputStream(FILENAME);

GZIPInputStream gzis= newGZIPInputStream(fin);

InputStreamReader xover= newInputStreamReader(gzis);

BufferedReader is= newBufferedReader(xover);

String line;while ((line = is.readLine()) != null)

System.out.println("Read: " + line);

9.目录和文件操作

//获取文件信息

exists(): 如 果文件存在,返回true

getCanonicalPath(): 获 取全名

getName(): 文件名

getParent(): 父 目录

canRead(): 如果文件可读,返回true

canWrite(): 如 果文件可写,返回true

lastModified(): 文 件更新时间

length(): 文件大小

isFile(): 如 果是文件,返回true

ifDirectory(): 如 果是目录,返回true

要 调用文件的这些方法,必须

File f= newFile(fileName);//创建文件

File f= new File("c:\\test\\mytesttxt");

f.createNewFile();//创建mytesttxt文件到test目录下//修改文件名

File f= new File("c:\\test\\mytesttxt");

f.renameTo(new File("c:\\test\\googletxt"));

把 mytest.txt修改成google.txt//删除文件

File f= new File("c:\\test\\mytesttxt");

f.delete();//临时文件

File f= new File("C:\\test"); //指定一个文件夹//在test文件夹中创建foo前缀,tmp后缀的临时文件

File tmp= FilecreateTempFile("foo", "tmp", f);

tmp.deleteOnExit();//在程序结束时删除该临时文件//更改文件属性

setReadOnly(): 设 置为只读

setlastModified(): 设置最后更改时间//列出当前文件夹的文件列表

String[] dir= new javaioFile("")list();

java.util.Arrays.sort(dir);for (int i = 0; i < dir.length; i++) {

System.out.println(dir[i]);

}//过滤文件列表

class OnlyJava implementsFilenameFilter {public booleanaccept(File dir, String s) {if (sendsWith("java") || sendsWith("class") || sendsWith("jar"))return true;

}

}//获取根目录

File[] rootDir=FilelistRoots();for (int i = 0; i < rootDir.length; i++) {

System.out.println(rootDir[i]);

}//创建新目录

new File("/home/ian/bin").mkdir(); //如果"/home/ian"存在,则可以创建bin目录

new File("/home/ian/bin").mkdirs(); //如果"/home/ian"不存在,会创建所有的目录

10. 国际化和本地化

//I18N资源

ResourceBundle rb= ResourceBundlegetBundle("Menus");

String label= rb.getString("exitlabel");//ResourceBundle相当于名值对,获取Menus按钮的区域属性

Menus_cnproperties: 不 同区域的属性文件//列出有效区域

Locale[] list=Locale.getAvailableLocales();//指定区域

Locale cnLocale=Locale.CHINA;//设置默认区域

Locale.setDefault(Locale.CHINA);//格式化消息

public classMessageFormatDemo {static Object[] data ={newjavautilDate(),"myfiletxt","could nto be opened"};public static voidmain(String[] args) {

String result= MessageFormat.format("At {0,time} on {0,date}, {1} {2}", data);

System.out.println(result);

}

}

输 出: At10:10:08 on 2009-6-18, myfiletxt could nto be opened//从资源文件中读消息

Widgetsproperties 在com.sean.cook.chap11下

ResourceBundle rb= ResourceBundlegetBundle("com.sean.cook.chap11.Widgets");

String propt= rb.getString("file.dialog.scant.open.string");

String result= MessageFormat.format(rb.getString("file.dialog.scant.open.format"), data);

11.网络客户端

//访问服务器

Socket socket= new Socket("127001", 8080);//todo something

socket.close();//查找网络地址

InetAddressgetByName(hostName).getHostAddress());//根据主机名得到IP地址

InetAddressgetByName(ipAddr).getHostName());//根据IP地址得到主机名//连接具体异常

UnknownHostException

NoRouteToHostException

ConnectException//Socket读写文本数据

BufferedReader in= new BufferedReader(newInputStreamReader(socket.getInputStream()));

String remoteTime=in.readline();

PrintWriter out= new PrintWriter(socket.getOutputStream(), true);

out.print("send message to client \r\n");

out.flush();//Socket读写二进制数据

DataInputStream in= new DataInputStream(newBufferedInputStream(socket.getInputStream()));long remoteTime = (long)(in.readUnsignedByte() << 24);

DataOutputStream out= new DataOutputStream(socket.getOutputStream(), true);//Socket读写串行化数据

ObjectInputStream in= new ObjectInputStream(newBufferedInputStream(socket.getInputStream()));

Object o=in.readObject();if (o instanceof Date) //验证对象类型

ObjectOutputStream out= new ObjectOutputStream(socket.getOutputStream(), true);//UDP数据报

private final static int PACKET_SIZE = 1024;

String host= "EV001B389673DE";

InetAddress serverAddr=InetAddressgetByName(host);

DatagramSocket socket= newDatagramSocket();byte[] buffer = new byte[PACKET_SIZE]; //分配数据缓冲空间

DatagramPacket packet= new DatagramPacket(buffer, PACKET_SIZE, serverAddr, 8080);

packet.setLength(PACKET_SIZE-1); //设置数据长度

socket.send(packet);

socket.receive(packet);//接收数据

12.服务器端: Socket

//创建ServerSocket

ServerSocket serverSocket;

Socket clientSocket;

serverSocket= new ServerSocket(9999);while ((clientSocket = serverSocket.accept()) != null) {

System.out.println("Accept from client " +s.getInetAddress());

sclose();

}//监听内部网

public static final short PORT = 9999;public static final String INSIDE_HOST = "acmewidgets-inside"; //网络接口名

public static final int BACKLOG = 10; //待发数

serverSocket= newServerSocket(PORT, BACKLOG, InetAddress.getByName(INSIDE_HOST));//返回相应对象

ServerSocket serverSocket= new ServerSocket(9999);;

Socket clientSocket;

BufferedReader in= null;

PrintWriter out= null;while (true) {

clientSocket=serverSocket.accept();

in= new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "8859_1"));

out= new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream(), "8859_1"), true);

String echoLine;while ((echoLine = in.readLine()) != null) {

System.out.println("Read " +echoLine);

out.print(echoLine+ "\r\n");

}

}

以 上例子返回字符串,如果返回二进制,则使用DataOutputStream;返回对象,使用ObjectOutputStream//处理多客户端

需要 把接收数据的处理放入多线程中public classEchoServerThreaded {public static final int ECHOPORT = 7;public static final int NUM_THREADS = 4;public static voidmain(String[] av) {newEchoServerThreaded(ECHOPORT, NUM_THREADS);

}public EchoServerThreaded2(int port, intnumThreads) {

ServerSocket servSock;

Socket clientSocket;try{

servSock= newServerSocket(ECHOPORT);

}catch(IOException e) {throw new RuntimeException("Could not create ServerSocket " +e);

}for (int i = 0; i < numThreads; i++) {newHandler(servSock, i)start();

}

}

}class Handler extendsThread {

ServerSocket servSock;intthreadNumber;

Handler(ServerSocket s,inti) {super();

servSock=s;

threadNumber=i;

setName("Thread " +threadNumber);

}public voidrun() {while (true) {try{

System.out.println(getName()+ " waiting");

Socket clientSocket;synchronized(servSock) {

clientSocket=servSockaccept();

}

System.out.println(getName()+ " starting, IP=" +clientSocket.getInetAddress());

BufferedReader is= new BufferedReader(newInputStreamReader(

clientSocket.getInputStream()));

PrintStream os= new PrintStream(clientSocket.getOutputStream(), true);

String line;while ((line = is.readLine()) != null) {

os.print(line+ "\r\n");

os.flush();

}

System.out.println(getName()+ " ENDED ");

clientSocket.close();

}catch(IOException ex) {

System.out.println(getName()+ ": IO Error on socket " +ex);return;

}

}

}

}//使用SSL和JSSE保护Web服务器

SSLServerSocketFactory ssf=(SSLServerSocketFactory)SSLServerSocketFactorygetDefault();

ServerSocket serverSocket= ssf.createServerSocket(8080);//Log4j

Level 级别: DEBUG< INFO < WARN < ERROR < FATAL

Appender: 输 出信息

ConsoleAppender: 输出控制台 Systemout//找到网络接口

Enumeration list=NetworkInterfacegetNetworkInterfaces();while(listhasMoreElements()) {

NetworkInterface iface=(NetworkInterface)listnextElement();

System.out.println(iface.getDisplayName());

Enumeration addrs=iface.getInetAddresses();while(addrshasMoreElements()) {

InetAddress addr=(InetAddress)addrsnextElement();

System.out.println(addr);

}

}

13.Java Mail

//发送Mail

protected String msgRecIp = "hxydream@163com";protected String msgSubject = "babytree";protected String msgCc = "nobody@erewhoncom";protected String msgBody = "test body";protectedSession session;protectedMessage msg;public voiddoSend() {//创建属性文件

Properties props= newProperties();

props.put("mailsmtphost", "mailhost");//创建Session对象

session= Session.getDefaultInstance(props, null);

session.setDebug(true);

msg= new MimeMessage(session); //创建邮件

msg.setFrom(new InternetAddress("nobody@hostdomain"));

InternetAddress toAddr= newInternetAddress(msgRecIp);

msg.addRecipient(MessageRecipientTypeTO, toAddr);

InternetAddress ccAddr= newInternetAddress(msgCc);

msg.addRecipient(MessageRecipientTypeCC, ccAddr);

msg.setSubject(msgSubject);

msg.setText(msgBody);

Transportsend(msg);

}//发送MIME邮件

Multipart mp= newMimeMultipart();

BodyPart textPart= newMimeBodyPart();

textPart.setText(message_body);//设置类型"text/plain"

BodyPart pixPart= newMimeBodyPart();

pixPart.setContent(html_data,"text/html");

mp.addBodyPart(textPart);

mp.addBodyPart(pixPart);

mesgsetContent(mp);

Transportsend(mesg);//读Mail

Store store=sessiongetStore(protocol);

store.connect(host, user, password);

Folder rf;

rf=store.getFolder(root);

rf=store.getDefaultFolder();

rf.open(FolderREAD_WRITE);

14.数据库访问

//JDO

Properties p= newProperties();

p.load(new FileInputStream("jdoproperties"));

PersistenceManagerFactory pmf=JDOHelpergetPersistenceManagerFactory(p);

PersistenceManager pm=pmfgetPersistenceManager();//提交数据

pm.currentTransaction()begin();if (o instanceofCollection) {

pm.makePersistentAll((Collection) o);

}else{

pm.makePersistent(o);

}

pm.currentTransaction()commit();

pm.close();//取出数据

Object[] data= new Object[3];

pm.retrieveAll(data);for (int i = 0; i < datalength; i++) {

System.out.println(data[i]);

}

pm.close();//数据操作

Class clz= ClassforName("oracle.jdbc.driver.OracleDriver");

String dbUrl= "jdbc:oracle:thin:@192168023:1521#:nms";

Connection conn= DriverManager.getConnection(dbUrl, "su", "1234");

Statement stmt=conn.createStatement();

ResultSet rs= stmt.executeQuery("select * from pmtable");while(rs.next()) {

String name= rs.getString(1);

String otherName= rs.getString("name");

}//使用PreparedStatement提高性能,除了查询,都使用executeUpdate执行操作

PreparedStatement pstmt= conn.prepareStatement("select * from pmtable where name = ?");

pstmt.setString(1, "sean");

ResultSet rs=pstmt.executeQuery();//调用存储过程

CallableStatement cs= conn.prepareCall("{ call ListDefunctUsers }");

ResultSet rs=cs.executeQuery();//显示数据库表信息

DatabaseMetaData meta=conngetMetaData();

meta.getDatabaseProductName();

meta.getDatabaseProductVersion();

meta.getDefaultTransactionIsolation();

15. XML

SAX: 在读取文档提取相应的标记事件(元素起始、元素结束、文档起始)

DOM: 在内存中构造与文档中元素相应的树,可以遍历、搜索、修改

DTD: 验证文档是否正确

JAXP: 用于XML处理的Java API

Castor: 开源项目,用于Java对象与XML映射

//从对象中生成XML

private final static String FILENAME = "serialxml";public static void main(String[] args) throwsIOException {

String a= "hard work and best callback";newSerialDemoXML().write(a);newSerialDemoXML().dump();

}public void write(Object obj) throwsIOException {

XMLEncoder os= new XMLEncoder(new BufferedOutputStream(newFileOutputStream(FILENAME)));

os.writeObject(obj);

os.close();

}public void dump() throwsIOException {

XMLDecoder out= new XMLDecoder(new BufferedInputStream(newFileInputStream(FILENAME)));

System.out.println(outreadObject());

out.close();

}

serialxml 格式内容如下:<?xml version="10" encoding="UTF-8"?>

hard work and best callback

控 制台输出

hard work and best callback//XSLT转换XML

XSLT 可以用来对输出格式进行各种控制

Transformer tx= TransformerFactory.newInstance().newTransformer(new StreamSource("peoplexml"));

tx.transform(new StreamSource("peoplexml"), new StreamResult("peoplehtml"));//用SAX解析XML - 主要用于查找关键元素,不用全文遍历

public SaxLister() throwsSAXException, IOException {

XMLReader parser= XMLReaderFactorycreateXMLReader("orgapachexercesparsersSAXParser");

parser.setContentHandler(newPeopleHandler());

parser.parse("C:\\StudySource\\javacooksrc2\\xml\\peoplexml");

}class PeopleHandler extendsDefaultHandler {boolean parent = false;boolean kids = false;public void startElement(String nsURI, String localName, String rawName, Attributes attr) throwsSAXException {

System.out.println("startElement: " + localName + "," +rawName);if (rawName.equalsIgnoreCase("name"))

parent= true;if (rawName.equalsIgnoreCase("children"))

kids= true;

}public void characters(char[] ch, int start, intlength) {if(parent) {

System.out.println("Parent: " + newString(ch, start, length));

parent= false;

}else if(kids) {

System.out.println("Children: " + newString(ch, start, length));

kids= false;

}

}public PeopleHandler() throwsSAXException {super();

}

}//DOM解析XML - 遍历整个树

String uri= "file:" + new File("C:\\StudySource\\javacooksrc2\\xml\\peoplexml").getAbsolutePath();

DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();

DocumentBuilder builder=factory.newDocumentBuilder();

Document doc=builder.parse(uri);

NodeList nodes=doc.getChildNodes();for (int i = 0; i < nodes.getLength(); i++) {

Node n=nodes.item(i);switch(n.getNodeType()) {caseNodeELEMENT_NODE://todo

break;caseNodeTEXT_NODE://todo

break;

}

}//使用DTD或者XSD验证

定 义好DTD或XSD文件

XmlDocument doc= XmlDocument.createXmlDocument(uri, true);//用DOM生成XML

DocumentBuilderFactory fact=DocumentBuilderFactory.newInstance();

DocumentBuilder parser=fact.newDocumentBuilder();

Document doc=parser.newDocument();

Node root= doc.createElement("Poem");

doc.appendChild(root);

Node stanza= doc.createElement("Stanza");

root.appendChild(stanza);

Node line= doc.createElement("Line");

stanza.appendChild(line);

line.appendChild(doccreateTextNode("Once, upon a midnight dreary"));

line= doc.createElement("Line");

stanz.aappendChild(line);

line.appendChild(doccreateTextNode("While I pondered, weak and weary"));

16.RMI

//a 定义 客户端与服务器之间的通信接口

public interface RemoteDate extendsRemote {public Date getRemoteDate() throwsRemoteException;public final static String LOOKUPNAME = "RemoteDate";

}//b 编 写RMI服务器

public class RemoteDateImpl extends UnicastRemoteObject implementsRemoteDate {public RemoteDateImpl() throwsRemoteException {super();

}public Date getRemoteDate() throwsRemoteException {return newDate();

}

}

RemoteDateImpl im= newRemoteDateImpl();

System.out.println("DateServer starting");

Namingre.bind(RemoteDateLOOKUPNAME, im);

System.out.println("DateServer ready");//c 运 行rmic生成stub

javac RemoteDateImpljava

rmic RemoteDateImpl//d 编 写客户端

netConn=(RemoteDate)Naminglookup(RemoteDate.LOOKUPNAME);

Date today=netConn.getRemoteDate();

System.out.println(today.toString());//e 确 保RMI注册表运行

rmi.registry//f 启 动服务器

java RemoteDateImpl//g 运 行客户端

java DateClient

17.包和包装机制

jar cvf /tmp/testjar //当前目录压缩到testjar中

jar xvf/tmp/testjar //把testjar解压到当前目录

从指定class运行jar文件

a Main-Class: HelloWord //注意中间有一个空格

b jar cvmf manifestmf hellojar HelloWorldclass

c java-jar hellojar

18.Java线程

//停止线程 - 不要使用stop()方法

private boolean done = false;public voidrun() {while (!done) {//todo

}

}public voidshutDown() {

done= true;

}//可 以调用shutDown()方法来结束线程//如果读取IO的时候出现堵塞,那么可以使用下面方法

public void shutDown() throwsIOException {if (io != null)

io.close();

}//启动一线程,等待控制台输入,使用join()方法来暂停当前线程,直到其他线程调用

Thread t= newThread() {public voidrun() {

System.out.println("Reading");try{

System.in.read();

}catch(IOException e) {

System.err.println(e);

}

System.out.println("Thread finished");

}

};

System.out.println("Starting");

t.start();

System.out.println("Joining");try{

t.join();

}catch(InterruptedException e) {

System.out.println("Who dares imterrupt my sleep?");

}

System.out.println("Main finished");//加锁保证同步

Lock lock= newReentrantLock();try{

lock.lock();//todo

}finally{

lock.unlock();

}

//线 程通信wait(), notify(), notifyAll()

19.内省或“命令类的类”

//反射

Class c= ClassforName("javalangString");

Constructor[] cons=c.getConstructors();for (int i = 0; i < cons.length; i++) {

System.out.println(cons[i].toString());

}

Method[] meths=cgetMethods();for (int i = 0; i < meths.length; i++) {

System.out.println(meths[i].toString());

}//动态装载类

Class c= ClassforName("java.lang.String");

Object obj=c.newInstance();//通过反射调用类的方法

classX {public voidmaster(String s) {

System.out.println("Working on \"" + s + "\"");

}

}

Class clx=Xclass;

Class[] argTypes={Stringclass};

Method worker= clx.getMethod("master", argTypes);

Object[] theData= {"Chocolate chips"};

worker.invoke(newX(), theData);

输 出: Working on"Chocolate chips"

20.Java与其他语言的结合

//执行CMD命令,在Eclipse控制台输出

Process p= RuntimegetRuntime()exec("C:/StudySource/vercmd");

p.waitFor();//等待命令执行完

BufferedReader br= new BufferedReader(newInputStreamReader(p.getInputStream()));

String s;while ((s = br.readLine()) != null)

System.out.println(s);//调用Jython - 计算220/7

BSFManager manager= newBSFManager();

String[] fntypes= {"py"};

manager.registerScriptingEngine("jython", "org.apache.bsfengines.jython.Jython.Engine", fntypes);

Object r= manager.eval("jython", "testString", 0, 0, "220/7");

System.out.println("Result type is " +rgetClass().getName());

System.out.println("Result value is " + r);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值