java 一些常用的代码(转载)
生活随笔
收集整理的這篇文章主要介紹了
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 }
?
?
轉載于:https://www.cnblogs.com/ling-2yuan/archive/2011/11/13/2247331.html
總結
以上是生活随笔為你收集整理的java 一些常用的代码(转载)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 无线通信协议小感
- 下一篇: jQuery美化select下拉框