java 一些常用的代码(转载)

Java 访问XML文件

 1 import java.io.*;
2 import javax.xml.parsers.DocumentBuilder;
3 import javax.xml.parsers.DocumentBuilderFactory;
4 import org.w3c.dom.Document;
5 import org.w3c.dom.Element;
6 import org.w3c.dom.Node;
7 import org.w3c.dom.NodeList;
8
9 public class xmljava
10 {
11
12 public static void main(String args[])
13 {
14 Element element=null;
15 File f =new File("a.xml");
16 DocumentBuilder db=null; //documentBuilder为抽象不能直接实例化(将XML文件转换为DOM文件)
17 DocumentBuilderFactory dbf=null;
18 try{
19
20 dbf= DocumentBuilderFactory.newInstance(); //返回documentBuilderFactory对象
21 db =dbf.newDocumentBuilder();//返回db对象用documentBuilderFatory对象获得返回documentBuildr对象
22
23 Document dt= db.parse(f); //得到一个DOM并返回给document对象
24 element = dt.getDocumentElement();//得到一个elment根元素
25
26 System.out.println("根元素:"+element.getNodeName()); //获得根节点
27
28 NodeList childNodes =element.getChildNodes() ; // 获得根元素下的子节点
29
30 for (int i = 0; i < childNodes.getLength(); i++) // 遍历这些子节点
31
32 {
33 Node node1 = childNodes.item(i); // childNodes.item(i); 获得每个对应位置i的结点
34
35 if ("Account".equals(node1.getNodeName()))
36 {
37 // 如果节点的名称为"Account",则输出Account元素属性type
38 System.out.println("\r\n找到一篇账号. 所属区域: " + node1.getAttributes().getNamedItem ("type").getNodeValue() + ". ");
39 NodeList nodeDetail = node1.getChildNodes(); // 获得<Accounts>下的节点
40 for (int j = 0; j < nodeDetail.getLength(); j++)
41 { // 遍历<Accounts>下的节点
42 Node detail = nodeDetail.item(j); // 获得<Accounts>元素每一个节点
43 if ("code".equals(detail.getNodeName())) // 输出code
44 System.out.println("卡号: " + detail.getTextContent());
45 else if ("pass".equals(detail.getNodeName())) // 输出pass
46 System.out.println("密码: " + detail.getTextContent());
47 else if ("name".equals(detail.getNodeName())) // 输出name
48 System.out.println("姓名: " + detail.getTextContent());
49 else if ("money".equals(detail.getNodeName())) // 输出money
50 System.out.println("余额: "+ detail.getTextContent());
51
52 }
53 }
54
55 }
56 }
57
58 catch(Exception e){System.out.println(e);}
59
60 }
61 }

 

java jdbc数据库连接

 

View Code
  1 import java.io.InputStream;
2 import java.sql.Connection;
3 import java.sql.DriverManager;
4 import java.sql.ResultSet;
5 import java.sql.SQLException;
6 import java.sql.Statement;
7 import java.util.Properties;
8
9
10 public class JDBConnection {
11 public Connection conn = null; // 声明Connection对象的实例
12 public Statement stmt = null; // 声明Statement对象的实例
13 public ResultSet rs = null; // 声明ResultSet对象的实例
14
15 private static String dbClassName = "com.microsoft.jdbc.sqlserver.SQLServerDriver";//定义保存数据库驱动的变量
16 private static String dbUrl = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=DB_ATM";
17 private static String dbUser = "sa";
18 private static String dbPwd = "sa";
19
20 public JDBConnection(String propertyFileName) {// 带属性文件名的构造方法
21 Properties prop = new Properties();// 属性集合对象
22 InputStream is = null;
23 try {
24 is = JDBConnection.class.getClassLoader().getResourceAsStream(
25 propertyFileName);// 属性文件输入流
26 // is = new FileInputStream("src/" + propertyFileName);
27 prop.load(is);// 将属性文件流装载到Properties对象中
28 is.close();// 关闭流
29 dbClassName = prop.getProperty("dbClassName");
30 dbUrl = prop.getProperty("dbUrl");
31 dbUser = prop.getProperty("dbUser");
32 dbPwd = prop.getProperty("dbPwd");
33 } catch (Exception e) {
34 System.out.println("属性文件 " + propertyFileName + " 打开失败!");
35 }
36 try {
37
38 Class.forName(dbClassName);// 1.注册驱动
39 } catch (ClassNotFoundException e) {
40 e.printStackTrace();
41 }
42 }
43
44 public JDBConnection() {// 默认的不带参数的构造函数
45 try {
46
47 Class.forName(dbClassName);// 1.注册驱动
48 } catch (ClassNotFoundException e) {
49 e.printStackTrace();
50 }
51 }
52
53 public static Connection getConnection() {
54 Connection conn = null;
55 try {
56 // Class.forName(dbClassName);// 1.注册驱动
57 conn = DriverManager.getConnection(dbUrl, dbUser, dbPwd);//2.建立与数据库的链接
58 } catch (Exception ee) {
59 ee.printStackTrace();
60 }
61 if (conn == null) {
62 System.err
63 .println("警告: DbConnectionManager.getConnection() 获得数据库链接失败.\r\n\r\n链接类型:"
64 + dbClassName
65 + "\r\n链接位置:"
66 + dbUrl
67 + "\r\n用户/密码"
68 + dbUser + "/" + dbPwd);
69 }
70 return conn;
71 }
72
73 /*
74 * 功能:执行查询语句
75 */
76 public ResultSet executeQuery(String sql) {
77 try { // 捕捉异常
78 conn = getConnection(); // 调用getConnection()方法构造Connection对象的一个实例conn
79 stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,//3.创建语句
80 ResultSet.CONCUR_READ_ONLY);
81 rs = stmt.executeQuery(sql);//4.执行查询
82 } catch (SQLException ex) {
83 System.err.println(ex.getMessage()); // 输出异常信息
84 }
85 return rs; // 返回结果集对象 5.结果处理
86 }
87
88 /*
89 * 功能:执行更新操作
90 */
91 public int executeUpdate(String sql) {
92 int result = 0; // 定义保存返回值的变量
93 try { // 捕捉异常
94 conn = getConnection(); // 调用getConnection()方法构造Connection对象的一个实例conn
95 stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
96 ResultSet.CONCUR_READ_ONLY);
97 result = stmt.executeUpdate(sql); // 执行更新操作
98 } catch (SQLException ex) {
99 result = 0; // 将保存返回值的变量赋值为0
100 }
101 return result; // 返回保存返回值的变量
102 }
103
104 /*
105 * 功能:关闭数据库的连接
106 */
107 public void close() {//6.释放资源
108 try { // 捕捉异常
109 try {
110 if (rs != null) { // 当ResultSet对象的实例rs不为空时
111 rs.close(); // 关闭ResultSet对象
112 }
113 } finally {
114 try {
115 if (stmt != null) { // 当Statement对象的实例stmt不为空时
116 stmt.close(); // 关闭Statement对象
117 }
118 } finally {
119 if (conn != null) { // 当Connection对象的实例conn不为空时
120 conn.close(); // 关闭Connection对象
121 }
122 }
123 }
124 } catch (Exception e) {
125 e.printStackTrace(System.err); // 输出异常信息
126 }
127 }
128
129 }

java访问资源文件

 

View Code
 1 import java.io.FileInputStream;   
2 import java.io.FileOutputStream;
3 import java.util.Properties;
4
5 public class PropertyEditor {
6 public static void main(String[] args) throws Exception {
7 Properties prop = new Properties();// 属性集合对象
8 FileInputStream fis = new FileInputStream("prop.properties");// 属性文件输入流 (相对于根目录下的文件名,要加上包名 “src/prop.properties”)
9 prop.load(fis);// 将属性文件流装载到Properties对象中
10 fis.close();// 关闭流
11
12 // 获取属性值,sitename已在文件中定义
13 System.out.println("获取属性值:sitename=" + prop.getProperty("sitename"));
14 // 获取属性值,country未在文件中定义,将在此程序中返回一个默认值,但并不修改属性文件
15 System.out.println("获取属性值:country=" + prop.getProperty("country", "中国"));
16
17 // 修改sitename的属性值
18 prop.setProperty("sitename", "中国");
19 // 添加一个新的属性studio
20 prop.setProperty("studio", "Boxcode Studio");
21 // 文件输出流
22 FileOutputStream fos = new FileOutputStream("prop.properties");
23 // 将Properties集合保存到流中
24 prop.store(fos, "Copyright (c) Boxcode Studio");
25 fos.close();// 关闭流
26 }
27 }

java日期处理bean

 

View Code
  1 import java.text.ParsePosition;
2 import java.text.SimpleDateFormat;
3 import java.util.Calendar;
4 import java.util.Date;
5 import java.util.GregorianCalendar;
6 import java.util.regex.Pattern;
7
8 import org.apache.commons.logging.Log;
9 import org.apache.commons.logging.LogFactory;
10
11
12 public class DateUtil {
13 protected static Log logger = LogFactory.getLog(DateUtil.class);
14
15 // 格式:年-月-日 小时:分钟:秒
16 public static final String FORMAT_ONE = "yyyy-MM-dd HH:mm:ss";
17
18 // 格式:年-月-日 小时:分钟
19 public static final String FORMAT_TWO = "yyyy-MM-dd HH:mm";
20
21 // 格式:年月日 小时分钟秒
22 public static final String FORMAT_THREE = "yyyyMMdd-HHmmss";
23
24 // 格式:年-月-日
25 public static final String LONG_DATE_FORMAT = "yyyy-MM-dd";
26
27 // 格式:月-日
28 public static final String SHORT_DATE_FORMAT = "MM-dd";
29
30 // 格式:小时:分钟:秒
31 public static final String LONG_TIME_FORMAT = "HH:mm:ss";
32
33 //格式:年-月
34 public static final String MONTG_DATE_FORMAT = "yyyy-MM";
35
36 // 年的加减
37 public static final int SUB_YEAR = Calendar.YEAR;
38
39 // 月加减
40 public static final int SUB_MONTH = Calendar.MONTH;
41
42 // 天的加减
43 public static final int SUB_DAY = Calendar.DATE;
44
45 // 小时的加减
46 public static final int SUB_HOUR = Calendar.HOUR;
47
48 // 分钟的加减
49 public static final int SUB_MINUTE = Calendar.MINUTE;
50
51 // 秒的加减
52 public static final int SUB_SECOND = Calendar.SECOND;
53
54 static final String dayNames[] = { "星期日", "星期一", "星期二", "星期三", "星期四",
55 "星期五", "星期六" };
56
57 @SuppressWarnings("unused")
58 private static final SimpleDateFormat timeFormat = new SimpleDateFormat(
59 "yyyy-MM-dd HH:mm:ss");
60
61 public DateUtil() {
62 }
63
64 /**
65 * 把符合日期格式的字符串转换为日期类型
66 */
67 public static java.util.Date stringtoDate(String dateStr, String format) {
68 Date d = null;
69 SimpleDateFormat formater = new SimpleDateFormat(format);
70 try {
71 formater.setLenient(false);
72 d = formater.parse(dateStr);
73 } catch (Exception e) {
74 // log.error(e);
75 d = null;
76 }
77 return d;
78 }
79
80 /**
81 * 把符合日期格式的字符串转换为日期类型
82 */
83 public static java.util.Date stringtoDate(String dateStr, String format,
84 ParsePosition pos) {
85 Date d = null;
86 SimpleDateFormat formater = new SimpleDateFormat(format);
87 try {
88 formater.setLenient(false);
89 d = formater.parse(dateStr, pos);
90 } catch (Exception e) {
91 d = null;
92 }
93 return d;
94 }
95
96 /**
97 * 把日期转换为字符串
98 */
99 public static String dateToString(java.util.Date date, String format) {
100 String result = "";
101 SimpleDateFormat formater = new SimpleDateFormat(format);
102 try {
103 result = formater.format(date);
104 } catch (Exception e) {
105 // log.error(e);
106 }
107 return result;
108 }
109
110 /**
111 * 获取当前时间的指定格式
112 */
113 public static String getCurrDate(String format) {
114 return dateToString(new Date(), format);
115 }
116
117 public static String dateSub(int dateKind, String dateStr, int amount) {
118 Date date = stringtoDate(dateStr, FORMAT_ONE);
119 Calendar calendar = Calendar.getInstance();
120 calendar.setTime(date);
121 calendar.add(dateKind, amount);
122 return dateToString(calendar.getTime(), FORMAT_ONE);
123 }
124
125 /**
126 * 两个日期相减
127 * @return 相减得到的秒数
128 */
129 public static long timeSub(String firstTime, String secTime) {
130 long first = stringtoDate(firstTime, FORMAT_ONE).getTime();
131 long second = stringtoDate(secTime, FORMAT_ONE).getTime();
132 return (second - first) / 1000;
133 }
134
135 /**
136 * 获得某月的天数
137 */
138 public static int getDaysOfMonth(String year, String month) {
139 int days = 0;
140 if (month.equals("1") || month.equals("3") || month.equals("5")
141 || month.equals("7") || month.equals("8") || month.equals("10")
142 || month.equals("12")) {
143 days = 31;
144 } else if (month.equals("4") || month.equals("6") || month.equals("9")
145 || month.equals("11")) {
146 days = 30;
147 } else {
148 if ((Integer.parseInt(year) % 4 == 0 && Integer.parseInt(year) % 100 != 0)
149 || Integer.parseInt(year) % 400 == 0) {
150 days = 29;
151 } else {
152 days = 28;
153 }
154 }
155
156 return days;
157 }
158
159 /**
160 * 获取某年某月的天数
161 */
162 public static int getDaysOfMonth(int year, int month) {
163 Calendar calendar = Calendar.getInstance();
164 calendar.set(year, month - 1, 1);
165 return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
166 }
167
168 /**
169 * 获得当前日期
170 */
171 public static int getToday() {
172 Calendar calendar = Calendar.getInstance();
173 return calendar.get(Calendar.DATE);
174 }
175
176 /**
177 * 获得当前月份
178 */
179 public static int getToMonth() {
180 Calendar calendar = Calendar.getInstance();
181 return calendar.get(Calendar.MONTH) + 1;
182 }
183
184 /**
185 * 获得当前年份
186 */
187 public static int getToYear() {
188 Calendar calendar = Calendar.getInstance();
189 return calendar.get(Calendar.YEAR);
190 }
191
192 /**
193 * 返回日期的天
194 */
195 public static int getDay(Date date) {
196 Calendar calendar = Calendar.getInstance();
197 calendar.setTime(date);
198 return calendar.get(Calendar.DATE);
199 }
200
201 /**
202 * 返回日期的年
203 */
204 public static int getYear(Date date) {
205 Calendar calendar = Calendar.getInstance();
206 calendar.setTime(date);
207 return calendar.get(Calendar.YEAR);
208 }
209
210 /**
211 * 返回日期的月份,1-12
212 */
213 public static int getMonth(Date date) {
214 Calendar calendar = Calendar.getInstance();
215 calendar.setTime(date);
216 return calendar.get(Calendar.MONTH) + 1;
217 }
218
219 /**
220 * 计算两个日期相差的天数,如果date2 > date1 返回正数,否则返回负数
221 */
222 public static long dayDiff(Date date1, Date date2) {
223 return (date2.getTime() - date1.getTime()) / 86400000;
224 }
225
226 /**
227 * 比较两个日期的年差
228 */
229 public static int yearDiff(String before, String after) {
230 Date beforeDay = stringtoDate(before, LONG_DATE_FORMAT);
231 Date afterDay = stringtoDate(after, LONG_DATE_FORMAT);
232 return getYear(afterDay) - getYear(beforeDay);
233 }
234
235 /**
236 * 比较指定日期与当前日期的差
237 */
238 public static int yearDiffCurr(String after) {
239 Date beforeDay = new Date();
240 Date afterDay = stringtoDate(after, LONG_DATE_FORMAT);
241 return getYear(beforeDay) - getYear(afterDay);
242 }
243
244 /**
245 * 比较指定日期与当前日期的差
246 */
247 public static long dayDiffCurr(String before) {
248 Date currDate = DateUtil.stringtoDate(currDay(), LONG_DATE_FORMAT);
249 Date beforeDate = stringtoDate(before, LONG_DATE_FORMAT);
250 return (currDate.getTime() - beforeDate.getTime()) / 86400000;
251
252 }
253
254 /**
255 * 获取每月的第一周
256 */
257 public static int getFirstWeekdayOfMonth(int year, int month) {
258 Calendar c = Calendar.getInstance();
259 c.setFirstDayOfWeek(Calendar.SATURDAY); // 星期天为第一天
260 c.set(year, month - 1, 1);
261 return c.get(Calendar.DAY_OF_WEEK);
262 }
263 /**
264 * 获取每月的最后一周
265 */
266 public static int getLastWeekdayOfMonth(int year, int month) {
267 Calendar c = Calendar.getInstance();
268 c.setFirstDayOfWeek(Calendar.SATURDAY); // 星期天为第一天
269 c.set(year, month - 1, getDaysOfMonth(year, month));
270 return c.get(Calendar.DAY_OF_WEEK);
271 }
272
273 /**
274 * 获得当前日期字符串,格式"yyyy_MM_dd_HH_mm_ss"
275 *
276 * @return
277 */
278 public static String getCurrent() {
279 Calendar cal = Calendar.getInstance();
280 cal.setTime(new Date());
281 int year = cal.get(Calendar.YEAR);
282 int month = cal.get(Calendar.MONTH) + 1;
283 int day = cal.get(Calendar.DAY_OF_MONTH);
284 int hour = cal.get(Calendar.HOUR_OF_DAY);
285 int minute = cal.get(Calendar.MINUTE);
286 int second = cal.get(Calendar.SECOND);
287 StringBuffer sb = new StringBuffer();
288 sb.append(year).append("_").append(StringUtil.addzero(month, 2))
289 .append("_").append(StringUtil.addzero(day, 2)).append("_")
290 .append(StringUtil.addzero(hour, 2)).append("_").append(
291 StringUtil.addzero(minute, 2)).append("_").append(
292 StringUtil.addzero(second, 2));
293 return sb.toString();
294 }
295
296 /**
297 * 获得当前日期字符串,格式"yyyy-MM-dd HH:mm:ss"
298 *
299 * @return
300 */
301 public static String getNow() {
302 Calendar today = Calendar.getInstance();
303 return dateToString(today.getTime(), FORMAT_ONE);
304 }
305
306
307
308 /**
309 * 判断日期是否有效,包括闰年的情况
310 *
311 * @param date
312 * YYYY-mm-dd
313 * @return
314 */
315 public static boolean isDate(String date) {
316 StringBuffer reg = new StringBuffer(
317 "^((\\d{2}(([02468][048])|([13579][26]))-?((((0?");
318 reg.append("[13578])|(1[02]))-?((0?[1-9])|([1-2][0-9])|(3[01])))");
319 reg.append("|(((0?[469])|(11))-?((0?[1-9])|([1-2][0-9])|(30)))|");
320 reg.append("(0?2-?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][12");
321 reg.append("35679])|([13579][01345789]))-?((((0?[13578])|(1[02]))");
322 reg.append("-?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))");
323 reg.append("-?((0?[1-9])|([1-2][0-9])|(30)))|(0?2-?((0?[");
324 reg.append("1-9])|(1[0-9])|(2[0-8]))))))");
325 Pattern p = Pattern.compile(reg.toString());
326 return p.matcher(date).matches();
327 }
328
329
330
331

java获取ip地址

View Code
 1 import java.awt.GridLayout;
2 import java.awt.event.ActionEvent;
3 import java.awt.event.ActionListener;
4 import java.net.InetAddress;
5 import java.net.UnknownHostException;
6 import javax.swing.JButton;
7 import javax.swing.JFrame;
8 import javax.swing.JLabel;
9 import javax.swing.JPanel;
10 import javax.swing.JTextField;
11
12 public class ip extends JFrame
13 implements ActionListener
14 {
15 private static final long serialVersionUID = 3339481369781127417L;
16 JButton jb1;
17 JButton jb2;
18 JButton jb3;
19 JPanel jp;
20 JLabel jl;
21 JLabel jl1;
22 JTextField jt;
23
24 public ip()
25 {
26 this.jp = new JPanel();
27 this.jl = new JLabel();
28 this.jl1 = new JLabel("您的域名:");
29 this.jb1 = new JButton("提交");
30 this.jb2 = new JButton("重置");
31 this.jb3 = new JButton("退出");
32 this.jt = new JTextField(20);
33 this.jb1.addActionListener(this);
34 this.jb2.addActionListener(this);
35 this.jb3.addActionListener(this);
36 this.jp.setLayout(new GridLayout(3, 2));
37 this.jp.add(this.jl1);
38 this.jp.add(this.jt);
39 this.jp.add(this.jb1);
40 this.jp.add(this.jl);
41 this.jp.add(this.jb2);
42 this.jp.add(this.jb3);
43
44 setBounds(200, 200, 500, 240);
45 add(this.jp);
46 setVisible(true);
47 setDefaultCloseOperation(3);
48 }
49
50 public static void main(String[] args)
51 {
52 new ip();
53 }
54
55 public void actionPerformed(ActionEvent e) {
56 if (e.getSource() == this.jb1) {
57 String url = this.jt.getText();
58 InetAddress ip = null;
59 try {
60 ip = InetAddress.getByName(url);
61 }
62 catch (UnknownHostException e1) {
63 e1.printStackTrace();
64 }
65 this.jl.setText(ip.toString());
66 }
67 else if (e.getSource() == this.jb2) {
68 this.jl.setText("");
69 this.jt.setText("");
70 } else {
71 System.exit(0);
72 }
73 }
74 }


 

 

posted @ 2011-11-13 16:11  凌云壮志  阅读(215)  评论(0编辑  收藏  举报