问题描述
java访问xml文件importjava.io.*;importjavax.xml.parsers.DocumentBuilder;importjavax.xml.parsers.DocumentBuilderFactory;importorg.w3c.dom.Document;importorg.w3c.dom.Element;importorg.w3c.dom.Node;importorg.w3c.dom.NodeList;publicclassxmljava{publicstaticvoidmain(Stringargs[]){Elementelement=null;Filef=newFile("a.xml");DocumentBuilderdb=null;//documentBuilder为抽象不能直接实例化(将XML文件转换为DOM文件)DocumentBuilderFactorydbf=null;try{dbf=DocumentBuilderFactory.newInstance();//返回documentBuilderFactory对象db=dbf.newDocumentBuilder();//返回db对象用documentBuilderFatory对象获得返回documentBuildr对象Documentdt=db.parse(f);//得到一个DOM并返回给document对象element=dt.getDocumentElement();//得到一个elment根元素System.out.println("根元素:"+element.getNodeName());//获得根节点NodeListchildNodes=element.getChildNodes();//获得根元素下的子节点for(inti=0;i<childNodes.getLength();i++)//遍历这些子节点{Nodenode1=childNodes.item(i);//childNodes.item(i);获得每个对应位置i的结点if("Account".equals(node1.getNodeName())){//如果节点的名称为"Account",则输出Account元素属性typeSystem.out.println("rn找到一篇账号.所属区域:"+node1.getAttributes().getNamedItem("type").getNodeValue()+".");NodeListnodeDetail=node1.getChildNodes();//获得<Accounts>下的节点for(intj=0;j<nodeDetail.getLength();j++){//遍历<Accounts>下的节点Nodedetail=nodeDetail.item(j);//获得<Accounts>元素每一个节点if("code".equals(detail.getNodeName()))//输出codeSystem.out.println("卡号:"+detail.getTextContent());elseif("pass".equals(detail.getNodeName()))//输出passSystem.out.println("密码:"+detail.getTextContent());elseif("name".equals(detail.getNodeName()))//输出nameSystem.out.println("姓名:"+detail.getTextContent());elseif("money".equals(detail.getNodeName()))//输出moneySystem.out.println("余额:"+detail.getTextContent());}}}}catch(Exceptione){System.out.println(e);}}}
<?xmlversion="1.0"encoding="gbk"?><Accounts><Accounttype="by0003"><code>100001</code><pass>123</pass><name>李四</name><money>1000000.00</money></Account><Accounttype="hz0001"><code>100002</code><pass>123</pass><name>张三</name><money>1000.00</money></Account></Accounts>
解决方案
解决方案二:
javajdbc数据库连接importjava.io.InputStream;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.Statement;importjava.util.Properties;publicclassJDBConnection{publicConnectionconn=null;//声明Connection对象的实例publicStatementstmt=null;//声明Statement对象的实例publicResultSetrs=null;//声明ResultSet对象的实例privatestaticStringdbClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver";//定义保存数据库驱动的变量privatestaticStringdbUrl="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=DB_ATM";privatestaticStringdbUser="sa";privatestaticStringdbPwd="sa";publicJDBConnection(StringpropertyFileName){//带属性文件名的构造方法Propertiesprop=newProperties();//属性集合对象InputStreamis=null;try{is=JDBConnection.class.getClassLoader().getResourceAsStream(propertyFileName);//属性文件输入流//is=newFileInputStream("src/"+propertyFileName);prop.load(is);//将属性文件流装载到Properties对象中is.close();//关闭流dbClassName=prop.getProperty("dbClassName");dbUrl=prop.getProperty("dbUrl");dbUser=prop.getProperty("dbUser");dbPwd=prop.getProperty("dbPwd");}catch(Exceptione){System.out.println("属性文件"+propertyFileName+"打开失败!");}try{Class.forName(dbClassName);//1.注册驱动}catch(ClassNotFoundExceptione){e.printStackTrace();}}publicJDBConnection(){//默认的不带参数的构造函数try{Class.forName(dbClassName);//1.注册驱动}catch(ClassNotFoundExceptione){e.printStackTrace();}}publicstaticConnectiongetConnection(){Connectionconn=null;try{//Class.forName(dbClassName);//1.注册驱动conn=DriverManager.getConnection(dbUrl,dbUser,dbPwd);//2.建立与数据库的链接}catch(Exceptionee){ee.printStackTrace();}if(conn==null){System.err.println("警告:DbConnectionManager.getConnection()获得数据库链接失败.rnrn链接类型:"+dbClassName+"rn链接位置:"+dbUrl+"rn用户/密码"+dbUser+"/"+dbPwd);}returnconn;}/**功能:执行查询语句*/publicResultSetexecuteQuery(Stringsql){try{//捕捉异常conn=getConnection();//调用getConnection()方法构造Connection对象的一个实例connstmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,//3.创建语句ResultSet.CONCUR_READ_ONLY);rs=stmt.executeQuery(sql);//4.执行查询}catch(SQLExceptionex){System.err.println(ex.getMessage());//输出异常信息}returnrs;//返回结果集对象5.结果处理}/**功能:执行更新操作*/publicintexecuteUpdate(Stringsql){intresult=0;//定义保存返回值的变量try{//捕捉异常conn=getConnection();//调用getConnection()方法构造Connection对象的一个实例connstmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);result=stmt.executeUpdate(sql);//执行更新操作}catch(SQLExceptionex){result=0;//将保存返回值的变量赋值为0}returnresult;//返回保存返回值的变量}/**功能:关闭数据库的连接*/publicvoidclose(){//6.释放资源try{//捕捉异常try{if(rs!=null){//当ResultSet对象的实例rs不为空时rs.close();//关闭ResultSet对象}}finally{try{if(stmt!=null){//当Statement对象的实例stmt不为空时stmt.close();//关闭Statement对象}}finally{if(conn!=null){//当Connection对象的实例conn不为空时conn.close();//关闭Connection对象}}}}catch(Exceptione){e.printStackTrace(System.err);//输出异常信息}}}
属性文件dbClassName=com.microsoft.jdbc.sqlserver.SQLServerDriverdbClassName2=com.mysql.jdbc.DriverdbPwd=sadbPwd2=rootdbUrl=jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=DB_ATMdbUrl2=jdbc:mysql://localhost:3306/db_atmdbUser=sadbUser2=root
解决方案三:
多谢楼主
解决方案四:
java自定义按钮外观importjava.awt.FlowLayout;importjavax.swing.JButton;importjavax.swing.JFrame;importjavax.swing.UIManager;importjavax.swing.plaf.synth.SynthLookAndFeel;publicclassMyButton{JFrameframe=newJFrame("TestButtons");JButtonjButton=newJButton("JButton");//按钮publicMyButton(){frame.setLayout(newFlowLayout());frame.getContentPane().add(jButton);}publicvoidshow(){frame.pack();frame.show();}publicstaticvoidmain(String[]args){MyButtontb=newMyButton();tb.show();SynthLookAndFeelslf=newSynthLookAndFeel();try{slf.load(MyButton.class.getResourceAsStream("mybutton.xml"),MyButton.class);UIManager.setLookAndFeel(slf);}catch(Exceptione){e.printStackTrace();return;}}}
<synth><styleid="mybutton"><state><imagePaintermethod="buttonBackground"path="mybutton.png"sourceInsets="361220"paintCenter="true"stretch="true"/><insetstop="3"left="6"bottom="12"right="20"/><fontname="Aharoni"size="16"/></state><propertykey="Button.margin"type="insets"value="0058"/></style><bindstyle="mybutton"type="region"key="Button"/></synth>
解决方案五:
java访问资源文件importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.util.Properties;publicclassPropertyEditor{publicstaticvoidmain(String[]args)throwsException{Propertiesprop=newProperties();//属性集合对象FileInputStreamfis=newFileInputStream("prop.properties");//属性文件输入流(相对于根目录下的文件名,要加上包名“src/prop.properties”)prop.load(fis);//将属性文件流装载到Properties对象中fis.close();//关闭流//获取属性值,sitename已在文件中定义System.out.println("获取属性值:sitename="+prop.getProperty("sitename"));//获取属性值,country未在文件中定义,将在此程序中返回一个默认值,但并不修改属性文件System.out.println("获取属性值:country="+prop.getProperty("country","中国"));//修改sitename的属性值prop.setProperty("sitename","中国");//添加一个新的属性studioprop.setProperty("studio","BoxcodeStudio");//文件输出流FileOutputStreamfos=newFileOutputStream("prop.properties");//将Properties集合保存到流中prop.store(fos,"Copyright(c)BoxcodeStudio");fos.close();//关闭流}}
资源文件sitename=u4E2Du56FDsiteurl=www.abcjava.comstudio=BoxcodeStudio
解决方案六:
先收藏先,以后有用得着的地方。
解决方案七:
java日期处理beanimportjava.text.ParsePosition;importjava.text.SimpleDateFormat;importjava.util.Calendar;importjava.util.Date;importjava.util.GregorianCalendar;importjava.util.regex.Pattern;importorg.apache.commons.logging.Log;importorg.apache.commons.logging.LogFactory;publicclassDateUtil{protectedstaticLoglogger=LogFactory.getLog(DateUtil.class);//格式:年-月-日小时:分钟:秒publicstaticfinalStringFORMAT_ONE="yyyy-MM-ddHH:mm:ss";//格式:年-月-日小时:分钟publicstaticfinalStringFORMAT_TWO="yyyy-MM-ddHH:mm";//格式:年月日小时分钟秒publicstaticfinalStringFORMAT_THREE="yyyyMMdd-HHmmss";//格式:年-月-日publicstaticfinalStringLONG_DATE_FORMAT="yyyy-MM-dd";//格式:月-日publicstaticfinalStringSHORT_DATE_FORMAT="MM-dd";//格式:小时:分钟:秒publicstaticfinalStringLONG_TIME_FORMAT="HH:mm:ss";//格式:年-月publicstaticfinalStringMONTG_DATE_FORMAT="yyyy-MM";//年的加减publicstaticfinalintSUB_YEAR=Calendar.YEAR;//月加减publicstaticfinalintSUB_MONTH=Calendar.MONTH;//天的加减publicstaticfinalintSUB_DAY=Calendar.DATE;//小时的加减publicstaticfinalintSUB_HOUR=Calendar.HOUR;//分钟的加减publicstaticfinalintSUB_MINUTE=Calendar.MINUTE;//秒的加减publicstaticfinalintSUB_SECOND=Calendar.SECOND;staticfinalStringdayNames[]={"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};@SuppressWarnings("unused")privatestaticfinalSimpleDateFormattimeFormat=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss");publicDateUtil(){}/***把符合日期格式的字符串转换为日期类型*/publicstaticjava.util.DatestringtoDate(StringdateStr,Stringformat){Dated=null;SimpleDateFormatformater=newSimpleDateFormat(format);try{formater.setLenient(false);d=formater.parse(dateStr);}catch(Exceptione){//log.error(e);d=null;}returnd;}/***把符合日期格式的字符串转换为日期类型*/publicstaticjava.util.DatestringtoDate(StringdateStr,Stringformat,ParsePositionpos){Dated=null;SimpleDateFormatformater=newSimpleDateFormat(format);try{formater.setLenient(false);d=formater.parse(dateStr,pos);}catch(Exceptione){d=null;}returnd;}/***把日期转换为字符串*/publicstaticStringdateToString(java.util.Datedate,Stringformat){Stringresult="";SimpleDateFormatformater=newSimpleDateFormat(format);try{result=formater.format(date);}catch(Exceptione){//log.error(e);}returnresult;}/***获取当前时间的指定格式*/publicstaticStringgetCurrDate(Stringformat){returndateToString(newDate(),format);}publicstaticStringdateSub(intdateKind,StringdateStr,intamount){Datedate=stringtoDate(dateStr,FORMAT_ONE);Calendarcalendar=Calendar.getInstance();calendar.setTime(date);calendar.add(dateKind,amount);returndateToString(calendar.getTime(),FORMAT_ONE);}/***两个日期相减*@return相减得到的秒数*/publicstaticlongtimeSub(StringfirstTime,StringsecTime){longfirst=stringtoDate(firstTime,FORMAT_ONE).getTime();longsecond=stringtoDate(secTime,FORMAT_ONE).getTime();return(second-first)/1000;}/***获得某月的天数*/publicstaticintgetDaysOfMonth(Stringyear,Stringmonth){intdays=0;if(month.equals("1")||month.equals("3")||month.equals("5")||month.equals("7")||month.equals("8")||month.equals("10")||month.equals("12")){days=31;}elseif(month.equals("4")||month.equals("6")||month.equals("9")||month.equals("11")){days=30;}else{if((Integer.parseInt(year)%4==0&&Integer.parseInt(year)%100!=0)||Integer.parseInt(year)%400==0){days=29;}else{days=28;}}returndays;}/***获取某年某月的天数*/publicstaticintgetDaysOfMonth(intyear,intmonth){Calendarcalendar=Calendar.getInstance();calendar.set(year,month-1,1);returncalendar.getActualMaximum(Calendar.DAY_OF_MONTH);}/***获得当前日期*/publicstaticintgetToday(){Calendarcalendar=Calendar.getInstance();returncalendar.get(Calendar.DATE);}/***获得当前月份*/publicstaticintgetToMonth(){Calendarcalendar=Calendar.getInstance();returncalendar.get(Calendar.MONTH)+1;}/***获得当前年份*/publicstaticintgetToYear(){Calendarcalendar=Calendar.getInstance();returncalendar.get(Calendar.YEAR);}/***返回日期的天*/publicstaticintgetDay(Datedate){Calendarcalendar=Calendar.getInstance();calendar.setTime(date);returncalendar.get(Calendar.DATE);}/***返回日期的年*/publicstaticintgetYear(Datedate){Calendarcalendar=Calendar.getInstance();calendar.setTime(date);returncalendar.get(Calendar.YEAR);}/***返回日期的月份,1-12*/publicstaticintgetMonth(Datedate){Calendarcalendar=Calendar.getInstance();calendar.setTime(date);returncalendar.get(Calendar.MONTH)+1;}/***计算两个日期相差的天数,如果date2>date1返回正数,否则返回负数*/publicstaticlongdayDiff(Datedate1,Datedate2){return(date2.getTime()-date1.getTime())/86400000;}/***比较两个日期的年差*/publicstaticintyearDiff(Stringbefore,Stringafter){DatebeforeDay=stringtoDate(before,LONG_DATE_FORMAT);DateafterDay=stringtoDate(after,LONG_DATE_FORMAT);returngetYear(afterDay)-getYear(beforeDay);}/***比较指定日期与当前日期的差*/publicstaticintyearDiffCurr(Stringafter){DatebeforeDay=newDate();DateafterDay=stringtoDate(after,LONG_DATE_FORMAT);returngetYear(beforeDay)-getYear(afterDay);}/***比较指定日期与当前日期的差*/publicstaticlongdayDiffCurr(Stringbefore){DatecurrDate=DateUtil.stringtoDate(currDay(),LONG_DATE_FORMAT);DatebeforeDate=stringtoDate(before,LONG_DATE_FORMAT);return(currDate.getTime()-beforeDate.getTime())/86400000;}/***获取每月的第一周*/publicstaticintgetFirstWeekdayOfMonth(intyear,intmonth){Calendarc=Calendar.getInstance();c.setFirstDayOfWeek(Calendar.SATURDAY);//星期天为第一天c.set(year,month-1,1);returnc.get(Calendar.DAY_OF_WEEK);}/***获取每月的最后一周*/publicstaticintgetLastWeekdayOfMonth(intyear,intmonth){Calendarc=Calendar.getInstance();c.setFirstDayOfWeek(Calendar.SATURDAY);//星期天为第一天c.set(year,month-1,getDaysOfMonth(year,month));returnc.get(Calendar.DAY_OF_WEEK);}/***获得当前日期字符串,格式"yyyy_MM_dd_HH_mm_ss"**@return*/publicstaticStringgetCurrent(){Calendarcal=Calendar.getInstance();cal.setTime(newDate());intyear=cal.get(Calendar.YEAR);intmonth=cal.get(Calendar.MONTH)+1;intday=cal.get(Calendar.DAY_OF_MONTH);inthour=cal.get(Calendar.HOUR_OF_DAY);intminute=cal.get(Calendar.MINUTE);intsecond=cal.get(Calendar.SECOND);StringBuffersb=newStringBuffer();sb.append(year).append("_").append(StringUtil.addzero(month,2)).append("_").append(StringUtil.addzero(day,2)).append("_").append(StringUtil.addzero(hour,2)).append("_").append(StringUtil.addzero(minute,2)).append("_").append(StringUtil.addzero(second,2));returnsb.toString();}/***获得当前日期字符串,格式"yyyy-MM-ddHH:mm:ss"**@return*/publicstaticStringgetNow(){Calendartoday=Calendar.getInstance();returndateToString(today.getTime(),FORMAT_ONE);}/***判断日期是否有效,包括闰年的情况**@paramdate*YYYY-mm-dd*@return*/publicstaticbooleanisDate(Stringdate){StringBufferreg=newStringBuffer("^((\d{2}(([02468][048])|([13579][26]))-?((((0?");reg.append("[13578])|(1[02]))-?((0?[1-9])|([1-2][0-9])|(3[01])))");reg.append("|(((0?[469])|(11))-?((0?[1-9])|([1-2][0-9])|(30)))|");reg.append("(0?2-?((0?[1-9])|([1-2][0-9])))))|(\d{2}(([02468][12");reg.append("35679])|([13579][01345789]))-?((((0?[13578])|(1[02]))");reg.append("-?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))");reg.append("-?((0?[1-9])|([1-2][0-9])|(30)))|(0?2-?((0?[");reg.append("1-9])|(1[0-9])|(2[0-8]))))))");Patternp=Pattern.compile(reg.toString());returnp.matcher(date).matches();}
解决方案八:
javados输入输出importjava.util.*;publicclassDaoXu{/***@paramargs*/publicstaticvoidmain(String[]args){//TODO自动生成方法存根System.out.println("请输入单个字符并回车:");Scannerc=newScanner(System.in);String[]ch=newString[5];for(inti=0;i<5;i++){ch[i]=c.next();}//Arrays.sort(ch);System.out.print("倒序输出:");for(intj=ch.length-1;j>=0;j--){System.out.print(ch[j]+"");}}}
解决方案九:
java获取ip地址importjava.awt.GridLayout;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.net.InetAddress;importjava.net.UnknownHostException;importjavax.swing.JButton;importjavax.swing.JFrame;importjavax.swing.JLabel;importjavax.swing.JPanel;importjavax.swing.JTextField;publicclassipextendsJFrameimplementsActionListener{privatestaticfinallongserialVersionUID=3339481369781127417L;JButtonjb1;JButtonjb2;JButtonjb3;JPaneljp;JLabeljl;JLabeljl1;JTextFieldjt;publicip(){this.jp=newJPanel();this.jl=newJLabel();this.jl1=newJLabel("您的域名:");this.jb1=newJButton("提交");this.jb2=newJButton("重置");this.jb3=newJButton("退出");this.jt=newJTextField(20);this.jb1.addActionListener(this);this.jb2.addActionListener(this);this.jb3.addActionListener(this);this.jp.setLayout(newGridLayout(3,2));this.jp.add(this.jl1);this.jp.add(this.jt);this.jp.add(this.jb1);this.jp.add(this.jl);this.jp.add(this.jb2);this.jp.add(this.jb3);setBounds(200,200,500,240);add(this.jp);setVisible(true);setDefaultCloseOperation(3);}publicstaticvoidmain(String[]args){newip();}publicvoidactionPerformed(ActionEvente){if(e.getSource()==this.jb1){Stringurl=this.jt.getText();InetAddressip=null;try{ip=InetAddress.getByName(url);}catch(UnknownHostExceptione1){e1.printStackTrace();}this.jl.setText(ip.toString());}elseif(e.getSource()==this.jb2){this.jl.setText("");this.jt.setText("");}else{System.exit(0);}}}
解决方案十:
感谢楼主!!!
解决方案十一:
java系统托盘的应用packagecom.msg;importjava.applet.Applet;importjava.applet.AudioClip;importjava.awt.AWTException;importjava.awt.Image;importjava.awt.MenuItem;importjava.awt.PopupMenu;importjava.awt.SystemTray;importjava.awt.TextArea;importjava.awt.TrayIcon;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.awt.event.MouseAdapter;importjava.awt.event.MouseEvent;importjava.awt.event.WindowAdapter;importjava.awt.event.WindowEvent;importjava.net.MalformedURLException;importjava.net.URL;importjava.util.Date;importjavax.swing.ImageIcon;importjavax.swing.JFrame;importjavax.swing.SwingUtilities;importjavax.swing.UIManager;importjavax.swing.UnsupportedLookAndFeelException;importorg.jvnet.substance.skin.SubstanceBusinessBlueSteelLookAndFeel;/****创建闪动的托盘图像*@authorEverest**/publicclassBickerTrayextendsJFrameimplementsRunnable{privatestaticfinallongserialVersionUID=-3115128552716619277L;privateSystemTraysysTray;//当前操作系统的托盘对象privateTrayIcontrayIcon;//当前对象的托盘privateImageIconicon=null;privateTextAreata=null;privatestaticintcount=1;//记录消息闪动的次数privatebooleanflag=false;//是否有新消息privatestaticinttimes=1;//接收消息次数publicBickerTray(){this.createTrayIcon();//创建托盘对象Imageimage=this.getToolkit().getImage(getRes("com/img/f32.gif"));this.setIconImage(image);init();}publicURLgetRes(Stringstr){returnthis.getClass().getClassLoader().getResource(str);}/***初始化窗体的方法*/publicvoidinit(){this.setTitle("消息盒子");ta=newTextArea("");ta.setEditable(false);this.add(ta);this.setSize(400,400);//this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setLocationRelativeTo(null);//添加窗口最小化事件,将托盘添加到操作系统的托盘/*this.addWindowListener(newWindowAdapter(){publicvoidwindowIconified(WindowEvente){addTrayIcon();}});*/addTrayIcon();this.setVisible(true);}/***添加托盘的方法*/publicvoidaddTrayIcon(){try{sysTray.add(trayIcon);//将托盘添加到操作系统的托盘setVisible(false);//使得当前的窗口隐藏newThread(this).start();}catch(AWTExceptione1){e1.printStackTrace();}}/***创建系统托盘的对象步骤:*1,获得当前操作系统的托盘对象*2,创建弹出菜单popupMenu*3,创建托盘图标icon*4,创建系统的托盘对象trayIcon*/publicvoidcreateTrayIcon(){sysTray=SystemTray.getSystemTray();//获得当前操作系统的托盘对象icon=newImageIcon(getRes("com/img/f17.gif"));//托盘图标PopupMenupopupMenu=newPopupMenu();//弹出菜单MenuItemmi=newMenuItem("打开");MenuItemexit=newMenuItem("退出");popupMenu.add(mi);popupMenu.add(exit);//为弹出菜单项添加事件mi.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){ta.setText(ta.getText()+"n==============================================n《通知》今天下午4:00到大礼堂开会。n第"+times+"次接收时间:"+newDate().toLocaleString());//设置通知消息内容BickerTray.this.setExtendedState(JFrame.NORMAL);BickerTray.this.setVisible(true);//显示窗口BickerTray.this.toFront();//显示窗口到最前端flag=false;//消息打开了count=0;times++;}});exit.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){System.exit(0);}});trayIcon=newTrayIcon(icon.getImage(),"消息盒子",popupMenu);/**添加鼠标监听器,当鼠标在托盘图标上双击时,默认显示窗口*/trayIcon.addMouseListener(newMouseAdapter(){publicvoidmouseClicked(MouseEvente){if(e.getClickCount()==2){//鼠标双击ta.setText(ta.getText()+"n==============================================n《通知》今天下午4:00到大礼堂开会。n第"+times+"次接收时间:"+newDate().toLocaleString());//设置通知消息内容BickerTray.this.setExtendedState(JFrame.NORMAL);BickerTray.this.setVisible(true);//显示窗口BickerTray.this.toFront();flag=false;//消息打开了count=0;times++;}}});}/***线程控制闪动*/publicvoidrun(){while(true){if(flag){//有新消息try{if(count==1){//播放消息提示音//AudioPlayerp=newAudioPlayer(getRes("file:com/sound/Msg.wav"));//p.play();p.stop();try{AudioClipp=Applet.newAudioClip(newURL("file:sound/msg.wav"));p.play();}catch(MalformedURLExceptione){e.printStackTrace();}}//闪动消息的空白时间this.trayIcon.setImage(newImageIcon("").getImage());Thread.sleep(500);//闪动消息的提示图片this.trayIcon.setImage(icon.getImage());Thread.sleep(500);}catch(Exceptione){e.printStackTrace();}count++;}else{//无消息或是消息已经打开过this.trayIcon.setImage(icon.getImage());try{Thread.sleep(20000);flag=true;}catch(InterruptedExceptione){e.printStackTrace();}}}}/***@paramargs*/publicstaticvoidmain(String[]args){JFrame.setDefaultLookAndFeelDecorated(true);try{UIManager.setLookAndFeel(newSubstanceBusinessBlueSteelLookAndFeel());}catch(UnsupportedLookAndFeelExceptione){e.printStackTrace();}SwingUtilities.invokeLater(newRunnable(){publicvoidrun(){newBickerTray();}});}}
解决方案十二:
JEditorPane使用技巧此组件使用EditorKit的实现来完成其操作。对于给予它的各种内容,它能有效地将其形态变换为适当的文本编辑器种类。该编辑器在任意给定时间的内容类型都由当前已安装的EditorKit确定。如果将内容设置为新的URL,则使用其类型来确定加载该内容所应使用的EditorKit。有多种方式可将内容加载到此组件中。1.可使用setText方法来初始化字符串组件。在这种情况下,将使用当前的EditorKit,且此类型为期望的内容类型。2.可使用read方法来初始化Reader组件。注意,如果内容类型为HTML,那么只有使用了<base>标记,或者设置了HTMLDocument上的Base属性时才能解析相关的引用(例如对于类似图像等内容)。在这种情况下,将使用当前的EditorKit,且此类型为期望的内容类型。3.可使用setPage方法来初始化URL组件。在这种情况下,将根据该URL来确定内容类型,并且设置为该内容类型所注册的EditorKit。构造函数JEditorPane()创建一个新的JEditorPane。JEditorPane(Stringurl)根据包含URL规范的字符串创建一个JEditorPane。JEditorPane(Stringtype,Stringtext)创建一个已初始化为给定文件的JEditorPane。JEditorPane(URLinitialPage)根据用作输入的指定URL创建一个JEditorPane。常用方法addHyperlinkListener(HyperlinkListenerlistener)为了通知所有的更改(例如选中和进入某个链接)而添加一个超链接侦听器。getContentType()获得设置此编辑器当前要处理的内容类型。getEditorKit()获取用于处理内容的、当前已安装的工具包。getPage()获得当前正在显示的URL。getPreferredSize()返回该JEditorPane的首选大小。getText()根据此编辑器的内容类型返回此TextComponent中所包含的文本。getStream(URLpage)获取给定URL的流,该URL是将要由setPage方法加载的。scrollToReference(Stringreference)将视图滚动到给定的参考位置(也就是正在显示的URL的UL.getRef方法所返回的值)。setContentType(Stringtype)设置此编辑器所处理的内容类型。setEditorKit(EditorKitkit)设置当前为处理内容而安装的工具包。setPage(Stringurl)设置当前要显示的URL。setPage(URLpage)设置当前要显示的URL。setText(Stringt)将此TextComponent的文本设置为指定内容,预期以此编辑器的内容类型格式提供该内容。
解决方案十三:
//窗口居中显示的方法this.setLocationRelativeTo(null);publicvoidsetLocationRelativeTo(Componentc)设置窗口相对于指定组件的位置。如果组件当前未显示,或者c为null,则此窗口将置于屏幕的中央。中点可以使用GraphicsEnvironment.getCenterPoint确定。如果该组件的底部在屏幕外,则将该窗口放置在Component最接近窗口中心的一侧。因此,如果Component在屏幕的右部,则Window将被放置在左部,反之亦然。
解决方案十四:
点到线段的最短距离privatedoublepointToLine(intx1,inty1,intx2,inty2,intx0,inty0){doublespace=0;doublea,b,c;a=lineSpace(x1,y1,x2,y2);//线段的长度b=lineSpace(x1,y1,x0,y0);//(x1,y1)到点的距离c=lineSpace(x2,y2,x0,y0);//(x2,y2)到点的距离if(c<=0.000001||b<=0.000001){space=0;returnspace;}if(a<=0.000001){space=b;returnspace;}if(c*c>=a*a+b*b){space=b;returnspace;}if(b*b>=a*a+c*c){space=c;returnspace;}doublep=(a+b+c)/2;//半周长doubles=Math.sqrt(p*(p-a)*(p-b)*(p-c));//海伦公式求面积space=2*s/a;//返回点到线的距离(利用三角形面积公式求高)returnspace;}//计算两点之间的距离privatedoublelineSpace(intx1,inty1,intx2,inty2){doublelineLength=0;lineLength=Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));returnlineLength;}
解决方案十五:
java各种数据库连接MySQL:StringDriver="com.mysql.jdbc.Driver";//驱动程序StringURL="jdbc:mysql://localhost:3306/db_name";//连接的URL,db_name为数据库名StringUsername="username";//用户名StringPassword="password";//密码Class.forName(Driver).newInstance();Connectioncon=DriverManager.getConnection(URL,Username,Password);MicrosoftSQLServer2.0驱动(3个jar的那个):StringDriver="com.microsoft.jdbc.sqlserver.SQLServerDriver";//连接SQL数据库的方法StringURL="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=db_name";//db_name为数据库名StringUsername="username";//用户名StringPassword="password";//密码Class.forName(Driver).newInstance();//加载数据可驱动Connectioncon=DriverManager.getConnection(URL,UserName,Password);//MicrosoftSQLServer3.0驱动(1个jar的那个)://老紫竹完善StringDriver="com.microsoft.sqlserver.jdbc.SQLServerDriver";//连接SQL数据库的方法StringURL="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=db_name";//db_name为数据库名StringUsername="username";//用户名StringPassword="password";//密码Class.forName(Driver).newInstance();//加载数据可驱动Connectioncon=DriverManager.getConnection(URL,UserName,Password);//Sysbase:StringDriver="com.sybase.jdbc.SybDriver";//驱动程序StringURL="jdbc:Sysbase://localhost:5007/db_name";//db_name为数据可名StringUsername="username";//用户名StringPassword="password";//密码Class.forName(Driver).newInstance();Connectioncon=DriverManager.getConnection(URL,Username,Password);Oracle(用thin模式):StringDriver="oracle.jdbc.driver.OracleDriver";//连接数据库的方法StringURL="jdbc:oracle:thin:@loaclhost:1521:orcl";//orcl为数据库的SIDStringUsername="username";//用户名StringPassword="password";//密码Class.forName(Driver).newInstance();//加载数据库驱动Connectioncon=DriverManager.getConnection(URL,Username,Password);PostgreSQL:StringDriver="org.postgresql.Driver";//连接数据库的方法StringURL="jdbc:postgresql://localhost/db_name";//db_name为数据可名StringUsername="username";//用户名StringPassword="password";//密码Class.forName(Driver).newInstance();Connectioncon=DriverManager.getConnection(URL,Username,Password);DB2:StringDriver="com.ibm.db2.jdbc.app.DB2.Driver";//连接具有DB2客户端的Provider实例//StringDriver="com.ibm.db2.jdbc.net.DB2.Driver";//连接不具有DB2客户端的Provider实例StringURL="jdbc:db2://localhost:5000/db_name";//db_name为数据可名StringUsername="username";//用户名StringPassword="password";//密码Class.forName(Driver).newInstance();Connectioncon=DriverManager.getConnection(URL,Username,Password);Informix:StringDriver="com.informix.jdbc.IfxDriver";StringURL="jdbc:Informix-sqli://localhost:1533/db_name:INFORMIXSER=myserver";//db_name为数据可名StringUsername="username";//用户名StringPassword="password";//密码Class.forName(Driver).newInstance();Connectioncon=DriverManager.getConnection(URL,Username,Password);JDBC-ODBC:StringDriver="sun.jdbc.odbc.JdbcOdbcDriver";StringURL="jdbc:odbc:dbsource";//dbsource为数据源名StringUsername="username";//用户名StringPassword="password";//密码Class.forName(Driver).newInstance();Connectioncon=DriverManager.getConnection(URL,Username,Password);
其他方案:
java哈弗曼编码的实现//哈弗曼编码的实现类publicclassHffmanCoding{privateintcharsAndWeight[][];//[][0]是字符,[][1]存放的是字符的权值(次数)privateinthfmcoding[][];//存放哈弗曼树privateinti=0;//循环变量privateStringhcs[];publicHffmanCoding(int[][]chars){//TODO构造方法charsAndWeight=newint[chars.length][2];charsAndWeight=chars;hfmcoding=newint[2*chars.length-1][4];//为哈弗曼树分配空间}//哈弗曼树的实现publicvoidcoding(){intn=charsAndWeight.length;if(n==0)return;intm=2*n-1;//初始化哈弗曼树for(i=0;i<n;i++){hfmcoding[i][0]=charsAndWeight[i][1];//初始化哈弗曼树的权值hfmcoding[i][1]=0;//初始化哈弗曼树的根节点hfmcoding[i][2]=0;//初始化哈弗曼树的左孩子hfmcoding[i][3]=0;//初始化哈弗曼树的右孩子}for(i=n;i<m;i++){hfmcoding[i][0]=0;//初始化哈弗曼树的权值hfmcoding[i][1]=0;//初始化哈弗曼树的根节点hfmcoding[i][2]=0;//初始化哈弗曼树的左孩子hfmcoding[i][3]=0;//初始化哈弗曼树的右孩子}//构建哈弗曼树for(i=n;i<m;i++){ints1[]=select(i);//在哈弗曼树中查找双亲为零的weight最小的节点hfmcoding[s1[0]][1]=i;//为哈弗曼树最小值付双亲hfmcoding[s1[1]][1]=i;hfmcoding[i][2]=s1[0];//新节点的左孩子hfmcoding[i][3]=s1[1];//新节点的右孩子hfmcoding[i][0]=hfmcoding[s1[0]][0]+hfmcoding[s1[1]][0];//新节点的权值是左右孩子的权值之和}}//查找双亲为零的weight最小的节点privateint[]select(intw){//TODOAuto-generatedmethodstubints[]={-1,-1},j=0;//s1最小权值且双亲为零的节点的序号,i是循环变量intmin1=32767,min2=32767;for(j=0;j<w;j++){if(hfmcoding[j][1]==0){//只在尚未构造二叉树的结点中查找(双亲为零的节点)if(hfmcoding[j][0]<min1){min2=min1;s[1]=s[0];min1=hfmcoding[j][0];s[0]=j;}elseif(hfmcoding[j][0]<min2){min2=hfmcoding[j][0];s[1]=j;}}}returns;}publicString[]CreateHCode(){//根据哈夫曼树求哈夫曼编码intn=charsAndWeight.length;inti,f,c;StringhcodeString="";hcs=newString[n];for(i=0;i<n;i++){//根据哈夫曼树求哈夫曼编码c=i;hcodeString="";f=hfmcoding[i][1];//f哈弗曼树的根节点while(f!=0){//循序直到树根结点if(hfmcoding[f][2]==c){//处理左孩子结点hcodeString+="0";}else{hcodeString+="1";}c=f;f=hfmcoding[f][1];}hcs[i]=newString(newStringBuffer(hcodeString).reverse());}returnhcs;}publicStringshow(Strings){//对字符串显示编码StringtextString="";charc[];intk=-1;c=newchar[s.length()];c=s.toCharArray();//将字符串转化为字符数组for(inti=0;i<c.length;i++){k=c[i];for(intj=0;j<charsAndWeight.length;j++)if(k==charsAndWeight[j][0])textString+=hcs[j];}returntextString;}//哈弗曼编码反编译publicStringreCoding(Strings){Stringtext="";//存放反编译后的字符intk=0,m=hfmcoding.length-1;//从根节点开始查询charc[];c=newchar[s.length()];c=s.toCharArray();k=m;for(inti=0;i<c.length;i++){if(c[i]=='0'){k=hfmcoding[k][2];//k的值为根节点左孩子的序号if(hfmcoding[k][2]==0&&hfmcoding[k][3]==0)//判断是不是叶子节点,条件(左右孩子都为零){text+=(char)charsAndWeight[k][0];k=m;}}if(c[i]=='1'){k=hfmcoding[k][3];//k的值为根节点右孩子的序号if(hfmcoding[k][2]==0&&hfmcoding[k][3]==0)//判断是不是叶子节点,条件(左右孩子都为零){text+=(char)charsAndWeight[k][0];k=m;}}}returntext;}}
其他方案:
/***人民币转成大写**@paramvalue*@returnString*/publicstaticStringhangeToBig(doublevalue){char[]hunit={'拾','佰','仟'};//段内位置表示char[]vunit={'万','亿'};//段名表示char[]digit={'零','壹','贰','叁','肆','伍','陆','柒','捌','玖'};//数字表示longmidVal=(long)(value*100);//转化成整形StringvalStr=String.valueOf(midVal);//转化成字符串Stringhead=valStr.substring(0,valStr.length()-2);//取整数部分Stringrail=valStr.substring(valStr.length()-2);//取小数部分Stringprefix="";//整数部分转化的结果Stringsuffix="";//小数部分转化的结果//处理小数点后面的数if(rail.equals("00")){//如果小数部分为0suffix="整";}else{suffix=digit[rail.charAt(0)-'0']+"角"+digit[rail.charAt(1)-'0']+"分";//否则把角分转化出来}//处理小数点前面的数char[]chDig=head.toCharArray();//把整数部分转化成字符数组charzero='0';//标志'0'表示出现过0bytezeroSerNum=0;//连续出现0的次数for(inti=0;i<chDig.length;i++){//循环处理每个数字intidx=(chDig.length-i-1)%4;//取段内位置intvidx=(chDig.length-i-1)/4;//取段位置if(chDig[i]=='0'){//如果当前字符是0zeroSerNum++;//连续0次数递增if(zero=='0'){//标志zero=digit[0];}elseif(idx==0&&vidx>0&&zeroSerNum<4){prefix+=vunit[vidx-1];zero='0';}continue;}zeroSerNum=0;//连续0次数清零if(zero!='0'){//如果标志不为0,则加上,例如万,亿什么的prefix+=zero;zero='0';}prefix+=digit[chDig[i]-'0'];//转化该数字表示if(idx>0)prefix+=hunit[idx-1];if(idx==0&&vidx>0){prefix+=vunit[vidx-1];//段结束位置应该加上段名如万,亿}}if(prefix.length()>0)prefix+='圆';//如果整数部分存在,则有圆的字样returnprefix+suffix;//返回正确表示}
其他方案:
遗传算法importjava.util.*;publicclassTsp{privateStringcityName[]={"北京","上海","天津","重庆","哈尔滨","长春","沈阳","呼和浩特","石家庄","太原","济南","郑州","西安","兰州","银川","西宁","乌鲁木齐","合肥","南京","杭州","长沙","南昌","武汉","成都","贵州","福建","台北","广州","海口","南宁","昆明","拉萨","香港","澳门"};//privateStringcityEnd[]=newString[34];privateintcityNum=cityName.length;//城市个数privateintpopSize=50;//种群数量privateintmaxgens=20000;//迭代次数privatedoublepxover=0.8;//交叉概率privatedoublepmultation=0.05;//变异概率privatelong[][]distance=newlong[cityNum][cityNum];privateintrange=2000;//用于判断何时停止的数组区间privateclassgenotype{intcity[]=newint[cityNum];//单个基因的城市序列longfitness;//该基因的适应度doubleselectP;//选择概率doubleexceptp;//期望概率intisSelected;//是否被选择}privategenotype[]citys=newgenotype[popSize];/***构造函数,初始化种群*/publicTsp(){for(inti=0;i<popSize;i++){citys[i]=newgenotype();int[]num=newint[cityNum];for(intj=0;j<cityNum;j++)num[j]=j;inttemp=cityNum;for(intj=0;j<cityNum;j++){intr=(int)(Math.random()*temp);citys[i].city[j]=num[r];num[r]=num[temp-1];temp--;}citys[i].fitness=0;citys[i].selectP=0;citys[i].exceptp=0;citys[i].isSelected=0;}initDistance();}/***计算每个种群每个基因个体的适应度,选择概率,期望概率,和是否被选择。*/publicvoidCalAll(){for(inti=0;i<popSize;i++){citys[i].fitness=0;citys[i].selectP=0;citys[i].exceptp=0;citys[i].isSelected=0;}CalFitness();CalSelectP();CalExceptP();CalIsSelected();}/***填充,将多选的填充到未选的个体当中*/publicvoidpad(){intbest=0;intbad=0;while(true){while(citys[best].isSelected<=1&&best<popSize-1)best++;while(citys[bad].isSelected!=0&&bad<popSize-1)bad++;for(inti=0;i<cityNum;i++)citys[bad].city[i]=citys[best].city[i];citys[best].isSelected--;citys[bad].isSelected++;bad++;if(best==popSize||bad==popSize)break;}}/***交叉主体函数*/publicvoidcrossover(){intx;inty;intpop=(int)(popSize*pxover/2);while(pop>0){x=(int)(Math.random()*popSize);y=(int)(Math.random()*popSize);executeCrossover(x,y);//xy两个体执行交叉pop--;}}/***执行交叉函数*@param个体x*@param个体y*对个体x和个体y执行佳点集的交叉,从而产生下一代城市序列*/privatevoidexecuteCrossover(intx,inty){intdimension=0;for(inti=0;i<cityNum;i++)if(citys[x].city[i]!=citys[y].city[i]){dimension++;}intdiffItem=0;double[]diff=newdouble[dimension];for(inti=0;i<cityNum;i++){if(citys[x].city[i]!=citys[y].city[i]){diff[diffItem]=citys[x].city[i];citys[x].city[i]=-1;citys[y].city[i]=-1;diffItem++;}}Arrays.sort(diff);double[]temp=newdouble[dimension];temp=gp(x,dimension);for(intk=0;k<dimension;k++)for(intj=0;j<dimension;j++)if(temp[j]==k){doubleitem=temp[k];temp[k]=temp[j];temp[j]=item;item=diff[k];diff[k]=diff[j];diff[j]=item;}inttempDimension=dimension;inttempi=0;while(tempDimension>0){if(citys[x].city[tempi]==-1){citys[x].city[tempi]=(int)diff[dimension-tempDimension];tempDimension--;}tempi++;}Arrays.sort(diff);temp=gp(y,dimension);for(intk=0;k<dimension;k++)for(intj=0;j<dimension;j++)if(temp[j]==k){doubleitem=temp[k];temp[k]=temp[j];temp[j]=item;item=diff[k];diff[k]=diff[j];diff[j]=item;}tempDimension=dimension;tempi=0;while(tempDimension>0){if(citys[y].city[tempi]==-1){citys[y].city[tempi]=(int)diff[dimension-tempDimension];tempDimension--;}tempi++;}}/***@paramindividual个体*@paramdimension维数*@return佳点集(用于交叉函数的交叉点)在executeCrossover()函数中使用*/privatedouble[]gp(intindividual,intdimension){double[]temp=newdouble[dimension];double[]temp1=newdouble[dimension];intp=2*dimension+3;while(!isSushu(p))p++;for(inti=0;i<dimension;i++){temp[i]=2*Math.cos(2*Math.PI*(i+1)/p)*(individual+1);temp[i]=temp[i]-(int)temp[i];if(temp[i]<0)temp[i]=1+temp[i];}for(inti=0;i<dimension;i++)temp1[i]=temp[i];Arrays.sort(temp1);//排序for(inti=0;i<dimension;i++)for(intj=0;j<dimension;j++)if(temp[j]==temp1[i])temp[j]=i;returntemp;}/***变异*/publicvoidmutate(){doublerandom;inttemp;inttemp1;inttemp2;for(inti=0;i<popSize;i++){random=Math.random();if(random<=pmultation){temp1=(int)(Math.random()*(cityNum));temp2=(int)(Math.random()*(cityNum));temp=citys[i].city[temp1];citys[i].city[temp1]=citys[i].city[temp2];citys[i].city[temp2]=temp;}}}/***打印当前代数的所有城市序列,以及其相关的参数*/publicvoidprint(){/***初始化各城市之间的距离*/privatevoidinitDistance(){for(inti=0;i<cityNum;i++){for(intj=0;j<cityNum;j++){distance[i][j]=Math.abs(i-j);}}}/***计算所有城市序列的适应度*/privatevoidCalFitness(){for(inti=0;i<popSize;i++){for(intj=0;j<cityNum-1;j++)citys[i].fitness+=distance[citys[i].city[j]][citys[i].city[j+1]];citys[i].fitness+=distance[citys[i].city[0]][citys[i].city[cityNum-1]];}}/***计算选择概率*/privatevoidCalSelectP(){longsum=0;for(inti=0;i<popSize;i++)sum+=citys[i].fitness;for(inti=0;i<popSize;i++)citys[i].selectP=(double)citys[i].fitness/sum;}/***计算期望概率*/privatevoidCalExceptP(){for(inti=0;i<popSize;i++)citys[i].exceptp=(double)citys[i].selectP*popSize;}/***计算该城市序列是否较优,较优则被选择,进入下一代*/privatevoidCalIsSelected(){intneedSelecte=popSize;for(inti=0;i<popSize;i++)if(citys[i].exceptp<1){citys[i].isSelected++;needSelecte--;}double[]temp=newdouble[popSize];for(inti=0;i<popSize;i++){//temp[i]=citys[i].exceptp-(int)citys[i].exceptp;//temp[i]*=10;temp[i]=citys[i].exceptp*10;}intj=0;while(needSelecte!=0){for(inti=0;i<popSize;i++){if((int)temp[i]==j){citys[i].isSelected++;needSelecte--;if(needSelecte==0)break;}}j++;}}/***@paramx*@return判断一个数是否是素数的函数*/privatebooleanisSushu(intx){if(x<2)returnfalse;for(inti=2;i<=x/2;i++)if(x%i==0&&x!=2)returnfalse;returntrue;}/***@paramx数组*@returnx数组的值是否全部相等,相等则表示x.length代的最优结果相同,则算法结束*/privatebooleanisSame(long[]x){for(inti=0;i<x.length-1;i++)if(x[i]!=x[i+1])returnfalse;returntrue;}/***打印任意代最优的路径序列*/privatevoidprintBestRoute(){CalAll();longtemp=citys[0].fitness;intindex=0;for(inti=1;i<popSize;i++){if(citys[i].fitness<temp){temp=citys[i].fitness;index=i;}}System.out.println();System.out.println("最佳路径的序列:");for(intj=0;j<cityNum;j++){StringcityEnd[]={cityName[citys[index].city[j]]};for(intm=0;m<cityEnd.length;m++){System.out.print(cityEnd[m]+"");}}//System.out.print(citys[index].city[j]+cityName[citys[index].city[j]]+"");//System.out.print(cityName[citys[index].city[j]]);System.out.println();}/***算法执行*/publicvoidrun(){long[]result=newlong[range];//result初始化为所有的数字都不相等for(inti=0;i<range;i++)result[i]=i;intindex=0;//数组中的位置intnum=1;//第num代while(maxgens>0){System.out.println("-----------------第"+num+"代-------------------------");CalAll();print();pad();crossover();mutate();maxgens--;longtemp=citys[0].fitness;for(inti=1;i<popSize;i++)if(citys[i].fitness<temp){temp=citys[i].fitness;}System.out.println("最优的解:"+temp);result[index]=temp;if(isSame(result))break;index++;if(index==range)index=0;num++;}printBestRoute();}/***@parama开始时间*@paramb结束时间*/publicvoidCalTime(Calendara,Calendarb){longx=b.getTimeInMillis()-a.getTimeInMillis();longy=x/1000;x=x-1000*y;System.out.println("算法执行时间:"+y+"."+x+"秒");}/***程序入口*/publicstaticvoidmain(String[]args){Calendara=Calendar.getInstance();//开始时间Tsptsp=newTsp();tsp.run();Calendarb=Calendar.getInstance();//结束时间tsp.CalTime(a,b);}}
其他方案:
挺不错的啊
其他方案:
java字符串解析StringTokenizertokenizer=newStringTokenizer(number,",");booleanbool=true;while(tokenizer.hasMoreTokens()){try{Double.valueOf(tokenizer.nextToken());}catch(Exceptione){bool=false;}}//将字符串转化为数组的方法intgv[];inti=0;StringTokenizertokenizer=newStringTokenizer(goodsVolume,",,");gv=newint[tokenizer.countTokens()];//动态的决定数组的长度while(tokenizer.hasMoreTokens()){Stringd=tokenizer.nextToken();gv[i]=Integer.valueOf(d);//将字符串转换为整型i++;}//字符串解析privateString[]stringAnalytical(Stringstr,StringdivisionChar){Stringstring[];inti=0;StringTokenizertokenizer=newStringTokenizer(str,divisionChar);string=newString[tokenizer.countTokens()];//动态的决定数组的长度while(tokenizer.hasMoreTokens()){string[i]=newString();string[i]=tokenizer.nextToken();i++;}returnstring;//返回字符串数组}intcountTokens()计算在生成异常之前可以调用此tokenizer的nextToken方法的次数。booleanhasMoreElements()返回与hasMoreTokens方法相同的值。booleanhasMoreTokens()测试此tokenizer的字符串中是否还有更多的可用标记。ObjectnextElement()除了其声明返回值是Object而不是String之外,它返回与nextToken方法相同的值。StringnextToken()返回此stringtokenizer的下一个标记。StringnextToken(Stringdelim)返回此stringtokenizer的字符串中的下一个标记。publicclassStringAnalytical{//字符串解析,将字符串转根据分割符换成字符串数组privateString[]stringAnalytical(Stringstring,charc){inti=0;intcount=0;if(string.indexOf(c)==-1)returnnewString[]{string};//如果不含分割符则返回字符本身char[]cs=string.toCharArray();intlength=cs.length;for(i=1;i<length-1;i++){//过滤掉第一个和最后一个是分隔符的情况if(cs[i]==c){count++;//得到分隔符的个数}}String[]strArray=newString[count+1];intk=0,j=0;Stringstr=string;if((k=str.indexOf(c))==0)//去掉第一个字符是分隔符的情况str=str.substring(k+1);if(str.indexOf(c)==-1)//检测是否含分隔符,如果不含则返回字符串returnnewString[]{str};while((k=str.indexOf(c))!=-1){//字符串含分割符的时候strArray[j++]=str.substring(0,k);str=str.substring(k+1);if((k=str.indexOf(c))==-1&&str.length()>0)strArray[j++]=str.substring(0);}returnstrArray;}publicvoidprintString(String[]s){System.out.println("*********************************");for(Stringstr:s)System.out.println(str);}publicstaticvoidmain(String[]args){String[]str=null;StringAnalyticalstring=newStringAnalytical();str=string.stringAnalytical("1aaa",'@');string.printString(str);str=string.stringAnalytical("2aaa@",'@');string.printString(str);str=string.stringAnalytical("@3aaa",'@');string.printString(str);str=string.stringAnalytical("4aaa@bbb",'@');string.printString(str);str=string.stringAnalytical("@5aaa@bbb",'@');string.printString(str);str=string.stringAnalytical("6aaa@bbb@",'@');string.printString(str);str=string.stringAnalytical("@7aaa@",'@');string.printString(str);str=string.stringAnalytical("@8aaa@bbb@",'@');string.printString(str);str=string.stringAnalytical("@9aaa@bbb@ccc",'@');string.printString(str);str=string.stringAnalytical("@10aaa@bbb@ccc@eee",'@');string.printString(str);}}
其他方案:
该回复于2011-04-01 08:37:13被版主删除
其他方案:
该回复于2011-04-01 08:34:34被版主删除
其他方案:
该回复于2011-04-01 08:39:31被版主删除
其他方案:
直不错建议打成jar包了,依赖的非标准的jar打进来呗
其他方案:
verygood
其他方案:
该回复于2011-04-01 10:32:59被版主删除
其他方案:
该回复于2011-04-01 10:34:06被版主删除
其他方案:
该回复于2011-04-01 10:34:05被版主删除
其他方案:
不自私的表现。
其他方案:
该回复于2011-04-01 11:19:01被版主删除
其他方案:
LZ辛苦了,顶起
其他方案:
该回复于2011-04-01 11:19:00被版主删除
其他方案:
该回复于2011-04-01 11:23:08被版主删除
其他方案:
该回复于2011-04-01 11:24:17被版主删除
其他方案:
该回复于2011-04-01 11:26:32被版主删除
其他方案:
该回复于2011-04-01 11:26:32被版主删除
其他方案:
该回复于2011-04-01 13:17:39被版主删除
其他方案:
该回复于2011-04-01 13:43:13被版主删除
其他方案:
该回复于2011-04-01 13:17:38被版主删除
其他方案:
好多...
其他方案:
该回复于2011-04-01 13:29:12被版主删除
其他方案:
Lz是个好人啊!!!这么多好用的东东!!!
其他方案:
该回复于2011-04-01 14:05:04被版主删除
其他方案:
该回复于2011-04-01 14:53:50被版主删除
其他方案:
该回复于2011-04-01 15:01:50被版主删除
其他方案:
淫才啊!!!LZ可不可以打个包,让后上载,让我们下啊!
其他方案:
十分感謝樓主的資料..
其他方案:
该回复于2011-04-01 15:12:01被版主删除
其他方案:
楼主好人!mark学习了
其他方案:
该回复于2011-04-01 14:54:49被版主删除
其他方案:
该回复于2011-04-01 16:36:59被版主删除