java常用功能例子總結(jié).docx_第1頁
java常用功能例子總結(jié).docx_第2頁
java常用功能例子總結(jié).docx_第3頁
java常用功能例子總結(jié).docx_第4頁
java常用功能例子總結(jié).docx_第5頁
已閱讀5頁,還剩13頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

1 JAVA1.1 JDK環(huán)境變量配置安裝完JDK后,需要配置環(huán)境變量。配置環(huán)境變量目的有三個(gè):第一,讓操作系統(tǒng)自動(dòng)查找編譯器、解釋器所在的路徑;第二,設(shè)置程序編譯和執(zhí)行時(shí)需要的類路徑;第三,Tomcat服務(wù)器安裝時(shí)需要知道虛擬機(jī)所在的路徑。(1)設(shè)置好path變量,使得我們能夠在系統(tǒng)中的任何地方運(yùn)行java應(yīng)用程序,比如javac、java、javah等等,這就要找到我們安裝JDK的目錄,比如我們的JDK安裝在C:jdk1.6.0目錄下,那么在C:jdk1.6.0bin目錄下就是我們常用的java應(yīng)用程序,我們就需要把C:jdk1.6.0bin這個(gè)目錄加到path環(huán)境變量里面。在系統(tǒng)變量里找到path變量,選擇-編輯;(里面已經(jīng)有很多的變量值,是在變量值的最前面加上C:jdk1.6.0bin;)變量名:path變量值:C:jdk1.6.0bin;(2)classpath環(huán)境變量,是當(dāng)我們?cè)陂_發(fā)java程序時(shí)需要引用別人寫好的類時(shí),要讓java解釋器知道到哪里去找這個(gè)類。通常,sun為我們提供了一些額外的豐富的類包,一個(gè)是dt.jar,一個(gè)是tools.jar,這兩個(gè)jar包都位于C:jdk1.6.0lib目錄下,所以通常我們都會(huì)把這兩個(gè)jar包加到我們的classpath環(huán)境變量中set classpath=.;C:jdk1.6.0libtools.jar;C:jdk1.6.0libdt.jar; C:jdk1.6.0lib在系統(tǒng)環(huán)境變量那一欄中點(diǎn)-新建classpath變量名:classpath變量值:.;%JAVA_HOME%libtools.jar;%JAVA_HOME%libdt.jar;(注意,CLASSPATH最前面是有個(gè)“.”的,表示當(dāng)前目錄,這樣當(dāng)我們運(yùn)行java AClass的時(shí)候,系統(tǒng)就會(huì)先在當(dāng)前目錄尋找AClass文件了。);(3)設(shè)置JAVA_HOME:一是為了方便引用,比如,JDK安裝在C:jdk1.6.0目錄里,則設(shè)置JAVA_HOME為該目錄路徑, 那么以后要使用這個(gè)路徑的時(shí)候,只需輸入%JAVA_HOME%即可,避免每次引用都輸入很長的路徑串;二則是歸一原則,當(dāng)JDK路徑改變的時(shí)候,僅需更改JAVA_HOME的變量值即可,否則,就要更改任何用絕對(duì)路徑引用JDK目錄的文檔,要是萬一沒有改全,某個(gè)程序找不到JDK,后果是可想而知的系統(tǒng)崩潰!三則是第三方軟件會(huì)引用約定好的JAVA_HOME變量,不然,你不能正常使用該軟件。在系統(tǒng)環(huán)境變量那一欄中點(diǎn)-新建JAVA_HOME (JAVA_HOME指向的是JDK的安裝路徑) 變量名:JAVA_HOME 變量值:C:jdk1.6.0(4)測(cè)試是否配置成功配置完成下面寫一個(gè)簡單的java程式來測(cè)試J2SDK是否已安裝成功:publicclassHelloWorld publicstaticvoidmain(Stringargs) ystem.out.println(Helloworld!); 將程式保存為文檔名為HelloWorld.java的文檔。打開命令提示符窗口,進(jìn)入到HelloWorld.java所在目錄,鍵入下面的命令javacHelloWorld.java javaHelloWorld此時(shí)若打印出來HelloWorld則安裝成功,若沒有打印出這句話,仔細(xì)檢查以上配置是否正確。1.2 Action1.2.1 Action傳參數(shù)1import javax.servlet.http.HttpServletRequest;HttpServletRequest request = ServletActionContext.getRequest();request.setAttribute(validity, 1);JSP中對(duì)應(yīng)取參數(shù):String validity=(String)request.getAttribute(validity);1.2.2 Action傳參數(shù)2import java.io.IOException;import java.io.PrintWriter; import javax.servlet.http.HttpServletResponse;HttpServletResponse response=ServletActionContext.getResponse();response.setCharacterEncoding(utf-8);try System.out.println(name is # + name);PrintWriter pw = response.getWriter();pw.print(result:名稱重復(fù),請(qǐng)重新輸入);pw.close(); catch (IOException e) e.printStackTrace();1.2.3 Action傳參數(shù)3Struts配置: Action:private String message;public String getMessage() return message;public void setMessage(String message) this.message = message;this.message=名稱重復(fù),請(qǐng)重新輸入;System.out.println(result is +this.message);return message;1.3 數(shù)據(jù)庫1.3.1 數(shù)據(jù)庫鏈接package com.edatongtu.utils;import java.sql.*; public class JdbcConnection public static String url =jdbc:oracle:thin::1521:ORCL; public static String username =lijuan; public static String password =123456; static try Class.forName(oracle.jdbc.driver.OracleDriver); catch (ClassNotFoundException e) throw new ExceptionInInitializerError(e); public static Connection getConnection() throws SQLException return DriverManager.getConnection(url, username, password); Connection con=JdbcConnection.getConnection();con.setAutoCommit(true); 自動(dòng)提交 Statement myStatement=con.createStatement();注:需導(dǎo)入 com.edatongtu.utils.JdbcConnection1.3.2 Sql語句1.數(shù)據(jù)選擇語句String sql=select * from tablestore where id=+lmid+; ResultSet rs=myStatement.executeQuery(sql);if(rs.next() element=rs.getString(element); 2.數(shù)據(jù)插入語句:String sql=”insert into refermodeltable (lmid,id,lmuniquename) values(”+lmid+”,”+id+”,”+uniquename+”)”;3.更新數(shù)據(jù):update tablestore set default_style=“+id+” where id=”+lmid+”4.刪除語句:delete from refermodeltable where id=”+lmid+”5.刪除表:drop table+表名6條件查詢:select classification_id,classification_name,classification_explain,(case if_default_classification when 0 then 否 when 1 then 是 end) if_default_classification from sys_ib_classification_system7.新建表: create table lijuantest2(id varchar(300) primary key,name varchar(300) not null)create table QT_4 (QUESTION_ID VARCHaR(50) primary key ,itembank_id varchar(50),question_type varchar(50),difficulty float(1),defaultpoint number(38),time_use number(38),knowledge_point_id varchar(50),editor_id varchar(50),update_time Date,explain varchar(50) default(無) ,statue number(38) default(1)8.更改表名:ALTER TABLE table111 RENAME TO table2229. or 和and 混合查詢SELECT * FROM Persons WHERELastName=Svendson AND (FirstName=Tove OR FirstName=Ola)10 case select 選擇查詢select rownum rn,cu.question_id,cu.defaultpoint,cu.time_use,cu.knowledge_point_id,cu.editor_id,cu.UPDATE_TIME,cu.TIME,cu.EXPLAIN,(case when difficulty0 then 簡單 when difficulty0.3 then 中等 when difficulty0.7 then 困難 end) DIFFICULTY, (case QUESTION_TYPE when xuanze then 選擇題 when panduan then 判斷題 when tiankong then 填空題 when jianda then 簡答題 end) QUESTION_TYPE from QT_BASICFIELD_lijuantest1 cu11 表格數(shù)據(jù)復(fù)制(普通數(shù)據(jù)和BLOB數(shù)據(jù)均可以復(fù)制)insert into QT_BLOBFIELD_LIJUANTEST2 SELECT * FROM QT_BLOBFIELD_LIJUANTEST1 WHERE QUESTION_ID=5e2393ca-b754-42e0-bd78-26088d069ed51.4 字符串處理1.4.1 list轉(zhuǎn)jsonJSONArray zNodes = JSONArray.fromObject( list );1.4.2 轉(zhuǎn)jsonJSONObject zNodes = JSONObject.fromObject( list );1.4.3 判斷字符串中是否有某個(gè)字段String ascs=ascs;if(ascs.indexOf(asc)!=-1)System.out.println(%);1.4.4 字符串轉(zhuǎn)換,去空格大寫defaultsort.trim().toUpperCase().equals(YES)1.4.5 字符串轉(zhuǎn)date型di.executeQuery(insert into QT_BASICFIELD_ + target_itembank+ fields(question_id,EDITOR_ID,TIME,QUESTION_TYPE) values(+questionid+, + cell24+ , + to_date(+cell12+,yyyy-MM-dd) + , + questiontype + );1.4.6 哈希表package com.edatongtu.utils;import java.util.HashMap;import java.util.Iterator;import java.util.Map;public class MapUtils public static Map getParameterMap(Map properties) / 返回值MapMap returnMap = new HashMap();Iterator entries = properties.entrySet().iterator();Map.Entry entry;String name = ;Object value = ;while (entries.hasNext() entry = (Map.Entry) entries.next();name = (String) entry.getKey();Object valueObj = entry.getValue();if(null = valueObj)value = ;else if(valueObj instanceof String)String values = (String)valueObj;for(int i=0;ivalues.length;i+)value = valuesi + ,;value = String.valueOf(value).substring(0, String.valueOf(value).length()-1);elsevalue = valueObj;returnMap.put(name, value);return returnMap;Map params=MapUtils.getParameterMap(request.getParameterMap();Iterator it = params.entrySet().iterator();while (it.hasNext() Map.Entry entry = (Map.Entry) it.next(); String paramName=(String)entry.getKey(); if(paramName.startsWith(main_) elementName=paramName.substring(main_.length(); style_element+=+elementName+:+elementName+,+elementTitle+:+params.get(fld_+elementName+_title)+,+isdisplay+:+params.get(fld_+elementName+_display)+,+isanchor+:+params.get(fld_+elementName+_anchor)+,; style_element=style_element.substring(0,style_element.length()-1);style_element=+style_element+;1.4.7 時(shí)間正則表達(dá)式 String eL = 0-94-0-92-0-92;Pattern p = Ppile(eL);Matcher m = p.matcher(bbb);boolean dateFlag = m.matches();if (!dateFlag) System.out.println(格式錯(cuò)誤);System.out.println(格式正確);1.4.8 ajax前臺(tái)向后臺(tái)傳數(shù)據(jù)亂碼問題后臺(tái)處理String str=new String(SortName.getBytes(iso-8859-1),utf-8);前臺(tái)處理:URL后跟參數(shù)是get方式,Data后aa:aapost方式應(yīng)采用post方式。1.5 IO1.5.1 將文件以blob寫入數(shù)據(jù)庫先插入再更新di.execute(insert into QT_BLOBFIELD_ + target_itembank+ values(+blob_Id+,empty_blob(),empty_blob();/插入空數(shù)據(jù)String TableName=QT_BLOBFIELD_ + target_itembank+ ;String IdField=question_id;String FieldName=questioncontent;File file3 = new File(d:+docname+.doc); InputStream in = null;/獲取試題文件流try in = new FileInputStream(file3); catch (FileNotFoundException e) e.printStackTrace(); service.exercuteInsertWithBlob(TableName, IdField,blob_Id, FieldName, in);public String exercuteInsertWithBlob(String TableName, String IdField,String Id, String FieldName, InputStream InStream) Connection connection = null;Statement statement = null;OutputStream outStream =null;Stringresult=true;StringSql=select +FieldName+ from +TableName+ where +IdField+=+Id+ for update;try connection = ConnPool.getConnection();statement = connection.createStatement();ResultSet rs = statement.executeQuery(Sql);if (rs.next() logger.debug(come in);/ 得到j(luò)ava.sql.Blob對(duì)象,然后Cast為oracle.sql.BLOBoracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob(1);/ 到數(shù)據(jù)庫的輸出流outStream = blob.getBinaryOutputStream();/ 將輸入流寫到輸出流byte b = new byteblob.getBufferSize();int len = 0;while (len = InStream.read(b) != -1) outStream.write(b, 0, len);elselogger.debug(dont come in);result=nodata;if(null!=InStream)InStream.close(); if(null!=outStream)outStream.flush(); outStream.close(); if(null!=connection)mit(); ConnPool.freeResource(rs, statement, connection); catch (Exception e) e.printStackTrace();result=error;return result;1.5.2 獲取inputstream流File file3 = new File(d:+docname+.doc); InputStream in = null;/獲取試題文件流try in = new FileInputStream(file3); catch (FileNotFoundException e) e.printStackTrace();1.5.3 InputStream Convert to fileFile file4 = new File(D:11111.doc);InputStream in = null;/ 獲取試題文件流try in = new FileInputStream(file4); catch (FileNotFoundException e) e.printStackTrace(); try File f=new File(D:lijuan111.doc); OutputStream out=new FileOutputStream(f); byte buf=new byte1024; int len; while(len=in.read(buf)0) out.write(buf,0,len); logger.debug(&*&); out.close(); in.close();/BufferedWriter bw = new BufferedWriter(new FileWriter(D:data.doc); /bw.write(in); catch (IOException e) / TODO Auto-generated catch blocke.printStackTrace(); 1.6 文件操作1.6.1 Java刪除文件String filePath = d:+newdocname+.doc;File file = new File(filePath);file.delete(); 1.6.2 Fileupload文件上傳 if (ServletFileUpload.isMultipartContent(request) DiskFileItemFactory dff = new DiskFileItemFactory(); dff.setRepository(tmpDir); dff.setSizeThreshold(1024000); ServletFileUpload upload = new ServletFileUpload(dff); upload.setFileSizeMax(5000000); upload.setSizeMax(10000000); List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext() FileItem fis = (FileItem) iter.next(); if (!fis.isFormField() & fis.getName().length() 0) String fileName = fis.getName(); realname=fis.getName().substring(0,fis.getName().lastIndexOf(.); suffix= fis.getName().substring( fis.getName().lastIndexOf(.); UniqueName=EDTTUUID.getUUID(); BufferedInputStream in = new BufferedInputStream(fis.getInputStream(); BufferedOutputStream out1 = new BufferedOutputStream( new FileOutputStream(new File(saveDir + + UniqueName+suffix); Streams.copy(in, out1, true); 1.7 Session1.7.1 Session 保存?zhèn)鬟f的數(shù)據(jù)if(request.getParameter(id)!=null)lmid=request.getParameter(id);session.setAttribute(LMID, lmid);elselmid=(String)session.getAttribute(LMID);1.8 常用1.8.1 自動(dòng)生成idSys_guid();1.8.2 UUID使用package com.edatongtu.utils;import com.eaio.uuid.UUID;public class EDTTUUID public static String getUUID()returnnew UUID().toString();id=EDTTUUID.getUUID();注:需導(dǎo)入 com.edatongtu.utils.EDTTUUID1.8.3 路勁存儲(chǔ)String savePath=/viewmodel;String dsavePath=request.getRealPath(savePath);1.8.4 批量刪除ResultSet rs=myStatement.executeQuery(select id from refermodeltable);String checkedIds=;while(rs.next()String chkItemValue=request.getParameter(chk+rs.getString(id);if(chkItemValue=null) else if(chkItemValue.equals(on) if(!checkedIds.equals() checkedIds+=,; checkedIds+=+rs.getString(id)+; if(!checkedIds.equals() String sql=delete from refermodeltable where id in (+checkedIds+); myStatement.execute(sql); rs.close(); myStatement.close(); con.close();1.9 接口和類1.9.1 接口定義:public interface SortService public String addSort(String message,String name,String identifier,String discription,String defaultsort) ;1.9.2 具體實(shí)現(xiàn):public class SortServiceImpl implements SortServicepublic String addSort(String message,String name,String identifier,String discription,String defaultsort) 1.9.3 調(diào)用類:方式一:SortService SortAddAction=new SortServiceImpl();SortAddAction.addSort(message,name,identifier,discription,defaultsort);方式二:運(yùn)用Spring依賴注入1)SortService SortAddAction=(SortService)BeanLoader.getBean(SortServiceImpl);SortAddAction.addSort(message,name,identifier,discription,defaultsort);Spring配置:2)private SortServiceImpl SortAddAction ;public SortServiceImpl getSortAddAction() return SortAddAction;public void setSortAddAction(SortServiceImpl sortAddAction) SortAddAction = sortAddAction;SortAddAction.addSort(message,name,identifier,discription,defaultsort);Spring配置:1.10 Jacob word操作參考資料中jacob函數(shù)JacobWordBeanServiceImpl wordBean = new JacobWordBeanServiceImpl();/ 檢查試題基本信息表格UUID newdocuuid = UUID.randomUUID(); String newdocname=newdocuuid.toString();wordBean.CreateDoc(newdocname);/ 創(chuàng)建一個(gè)新文件wordBean.OpenFile(d:+newdocname+.doc);wordBean.SetVisible(true); / 是否前臺(tái)打開word 程序,或者后臺(tái)運(yùn)行wordBean.copyTableFromAnotherDoc(d:xiaokai.doc, 1);UUID savedocuuid = UUID.randomUUID(); String savedocname=newdocuuid.toString();wordBean.saveFileAs(d:+savedocname+.doc);/ 保存第一個(gè)表格,必須另存,不然會(huì)在前臺(tái)是否保存word,則無法執(zhí)行刪除工作/ 檢查表格行數(shù)列數(shù)是否正確int rowCount = wordBean.gettableRow();/ 表格行數(shù)int colCount = wordBean.gettableColumn();/ 表格列數(shù)int cols1 = wordBean.getCols(1);/ 第一行列數(shù)int cols2 = wordBean.getCols(2);/ 第二行列數(shù) /* * * 名稱:gettableColumn * 說明:獲取表格列數(shù) * 參數(shù):param anotherDocPath * 參數(shù):param tableIndex 設(shè)定文件 * 返回值:void 返回類型 * param anotherDocPath * param tableIndex * author:lijuan */ public int gettableColumn() Dispatch tables = Dispatch.get(document, Tables).toDispatch(); int tableCount = Dispatch.get(tables, Count).getInt(); / document中的表格數(shù)量 Dispatch table = Dispatch.call(tables, Item, new Variant(tableCount) .toDispatch();/ 文檔中最后一個(gè)table Dispatch cols = Dispatch.get(table, Columns).toDispatch(); int colCount = Dispatch.get(cols, Count).getInt(); return colCount; /* * * 名稱:gettableRow * 說明:TODO(這里用一句話描述這個(gè)方法的作用) * 參數(shù):return 設(shè)定文件 * 返回值:int 返回類型 * return * author:lijuan */ public int gettableRow() Dispatch tables = Dispatch.get(document, Tables).toDispatch(); int tableCount = Dispatch.get(tables, Count).getInt(); / document中的表格數(shù)量 Dispatch table = Dispatch.call(tables, Item, new Variant(tableCount) .toDispatch();/ 文檔中最后一個(gè)table Dispatch rows = Dispatch.get(table, Rows).toDispatch(); / 此表的所有行, int rowCount = Dispatch.get(rows, Count).getInt(); return rowCount; /* * * 名稱:getCols * 說明:獲取某一行的列數(shù) * 參數(shù):return 設(shè)定文件 * 返回值:int 返回類型 * return * author:lijuan */ public int getCols(int a) Dispatch tables = Dispatch.get(document, Tables).toDispatch(); int tableCount = Dispatch.get(tables, Count).getInt(); / document中的表格數(shù)量 Dispatch table = Dispatch.call(tables, Item, new Variant(tableCo

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論