- 浏览: 10717 次
- 性别:
- 来自: 烟台
文章分类
最新评论
-
wangshutaohabao:
为什么我选择 license提示无效 求指教啊
spket -
dreamhunter:
sub.request();//调用真实对象的request( ...
java 反射 动态代理
//1. 字符串有整型的相互转换
002 String a = String.valueOf(2); //integer to numeric string
003 int i = Integer.parseInt(a); //numeric string to an int
004
005 //2. 向文件末尾添加内容
006 BufferedWriter out = null;
007 try {
008 out = new BufferedWriter(new FileWriter(”filename”, true));
009 out.write(”aString”);
010 } catch (IOException e) {
011 // error processing code
012
013 } finally {
014 if (out != null) {
015 out.close();
016 }
017
018 }
019
020 //3. 得到当前方法的名字
021 String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
022
023 //4. 转字符串到日期
024 java.util.Date = java.text.DateFormat.getDateInstance().parse(date String);
025 //或者是:
026 SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );
027 Date date = format.parse( myString );
028
029 //5. 使用JDBC链接Oracle
030 public class OracleJdbcTest
031 {
032 String driverClass = "oracle.jdbc.driver.OracleDriver";
033
034 Connection con;
035
036 public void init(FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException
037 {
038 Properties props = new Properties();
039 props.load(fs);
040 String url = props.getProperty("db.url");
041 String userName = props.getProperty("db.user");
042 String password = props.getProperty("db.password");
043 Class.forName(driverClass);
044
045 con=DriverManager.getConnection(url, userName, password);
046 }
047
048 public void fetch() throws SQLException, IOException
049 {
050 PreparedStatement ps = con.prepareStatement("select SYSDATE from dual");
051 ResultSet rs = ps.executeQuery();
052
053 while (rs.next())
054 {
055 // do the thing you do
056 }
057 rs.close();
058 ps.close();
059 }
060
061 public static void main(String[] args)
062 {
063 OracleJdbcTest test = new OracleJdbcTest();
064 test.init();
065 test.fetch();
066 }
067 }
068
069 6. 把 Java util.Date 转成 sql.Date
070 java.util.Date utilDate = new java.util.Date();
071 java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
072
073 //7. 使用NIO进行快速的文件拷贝
074 public static void fileCopy( File in, File out )
075 throws IOException
076 {
077 FileChannel inChannel = new FileInputStream( in ).getChannel();
078 FileChannel outChannel = new FileOutputStream( out ).getChannel();
079 try
080 {
081 // inChannel.transferTo(0, inChannel.size(), outChannel); // original -- apparently has trouble copying large files on Windows
082
083 // magic number for Windows, 64Mb - 32Kb)
084 int maxCount = (64 * 1024 * 1024) - (32 * 1024);
085 long size = inChannel.size();
086 long position = 0;
087 while ( position < size )
088 {
089 position += inChannel.transferTo( position, maxCount, outChannel );
090 }
091 }
092 finally
093 {
094 if ( inChannel != null )
095 {
096 inChannel.close();
097 }
098 if ( outChannel != null )
099 {
100 outChannel.close();
101 }
102 }
103 }
104
105 //8. 创建图片的缩略图
106 private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename)
107 throws InterruptedException, FileNotFoundException, IOException
108 {
109 // load image from filename
110 Image image = Toolkit.getDefaultToolkit().getImage(filename);
111 MediaTracker mediaTracker = new MediaTracker(new Container());
112 mediaTracker.addImage(image, 0);
113 mediaTracker.waitForID(0);
114 // use this to test for errors at this point: System.out.println(mediaTracker.isErrorAny());
115
116 // determine thumbnail size from WIDTH and HEIGHT
117 double thumbRatio = (double)thumbWidth / (double)thumbHeight;
118 int imageWidth = image.getWidth(null);
119 int imageHeight = image.getHeight(null);
120 double imageRatio = (double)imageWidth / (double)imageHeight;
121 if (thumbRatio < imageRatio) {
122 thumbHeight = (int)(thumbWidth / imageRatio);
123 } else {
124 thumbWidth = (int)(thumbHeight * imageRatio);
125 }
126
127 // draw original image to thumbnail image object and
128 // scale it to the new size on-the-fly
129 BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
130 Graphics2D graphics2D = thumbImage.createGraphics();
131 graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
132 graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
133
134 // save thumbnail image to outFilename
135 BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename));
136 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
137 JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
138 quality = Math.max(0, Math.min(quality, 100));
139 param.setQuality((float)quality / 100.0f, false);
140 encoder.setJPEGEncodeParam(param);
141 encoder.encode(thumbImage);
142 out.close();
143 }
144
145 //9. 创建 JSON 格式的数据
146 import org.json.JSONObject;
147 ...
148 ...
149 JSONObject json = new JSONObject();
150 json.put("city", "Mumbai");
151 json.put("country", "India");
152 ...
153 String output = json.toString();
154 ...
155
156 //10. 使用iText JAR生成PDF
157 import java.io.File;
158 import java.io.FileOutputStream;
159 import java.io.OutputStream;
160 import java.util.Date;
161
162 import com.lowagie.text.Document;
163 import com.lowagie.text.Paragraph;
164 import com.lowagie.text.pdf.PdfWriter;
165
166 public class GeneratePDF {
167
168 public static void main(String[] args) {
169 try {
170 OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
171
172 Document document = new Document();
173 PdfWriter.getInstance(document, file);
174 document.open();
175 document.add(new Paragraph("Hello Kiran"));
176 document.add(new Paragraph(new Date().toString()));
177
178 document.close();
179 file.close();
180
181 } catch (Exception e) {
182
183 e.printStackTrace();
184 }
185 }
186 }
187
188 //11. HTTP 代理设置
189 System.getProperties().put("http.proxyHost", "someProxyURL");
190 System.getProperties().put("http.proxyPort", "someProxyPort");
191 System.getProperties().put("http.proxyUser", "someUserName");
192 System.getProperties().put("http.proxyPassword", "somePassword");
193
194 //12. 单实例Singleton 示例
195 public class SimpleSingleton {
196 private static SimpleSingleton singleInstance = new SimpleSingleton();
197
198 //Marking default constructor private
199 //to avoid direct instantiation.
200 private SimpleSingleton() {
201 }
202
203 //Get instance for class SimpleSingleton
204 public static SimpleSingleton getInstance() {
205
206 return singleInstance;
207 }
208 }
209
210 //另一种实现
211
212 public enum SimpleSingleton {
213 INSTANCE;
214 public void doSomething() {
215 }
216 }
217
218 //Call the method from Singleton:
219 SimpleSingleton.INSTANCE.doSomething();
220
221 //13. 抓屏程序
222 import java.awt.Dimension;
223 import java.awt.Rectangle;
224 import java.awt.Robot;
225 import java.awt.Toolkit;
226 import java.awt.image.BufferedImage;
227 import javax.imageio.ImageIO;
228 import java.io.File;
229
230 ...
231 public void captureScreen(String fileName) throws Exception {
232
233 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
234 Rectangle screenRectangle = new Rectangle(screenSize);
235 Robot robot = new Robot();
236 BufferedImage image = robot.createScreenCapture(screenRectangle);
237 ImageIO.write(image, "png", new File(fileName));
238
239 }
240 //14. 列出文件和目录
241 File dir = new File("directoryName");
242 String[] children = dir.list();
243 if (children == null) {
244 // Either dir does not exist or is not a directory
245 } else {
246 for (int i=0; i < children.length; i++) {
247 // Get filename of file or directory
248 String filename = children[i];
249 }
250 }
251
252 // It is also possible to filter the list of returned files.
253 // This example does not return any files that start with `.’.
254 FilenameFilter filter = new FilenameFilter() {
255 public boolean accept(File dir, String name) {
256 return !name.startsWith(".");
257 }
258 };
259 children = dir.list(filter);
260
261 // The list of files can also be retrieved as File objects
262 File[] files = dir.listFiles();
263
264 // This filter only returns directories
265 FileFilter fileFilter = new FileFilter() {
266 public boolean accept(File file) {
267 return file.isDirectory();
268 }
269 };
270 files = dir.listFiles(fileFilter);
271
272 //15. 创建ZIP和JAR文件
273
274 import java.util.zip.*;
275 import java.io.*;
276
277 public class ZipIt {
278 public static void main(String args[]) throws IOException {
279 if (args.length < 2) {
280 System.err.println("usage: java ZipIt Zip.zip file1 file2 file3");
281 System.exit(-1);
282 }
283 File zipFile = new File(args[0]);
284 if (zipFile.exists()) {
285 System.err.println("Zip file already exists, please try another");
286 System.exit(-2);
287 }
288 FileOutputStream fos = new FileOutputStream(zipFile);
289 ZipOutputStream zos = new ZipOutputStream(fos);
290 int bytesRead;
291 byte[] buffer = new byte[1024];
292 CRC32 crc = new CRC32();
293 for (int i=1, n=args.length; i < n; i++) {
294 String name = args[i];
295 File file = new File(name);
296 if (!file.exists()) {
297 System.err.println("Skipping: " + name);
298 continue;
299 }
300 BufferedInputStream bis = new BufferedInputStream(
301 new FileInputStream(file));
302 crc.reset();
303 while ((bytesRead = bis.read(buffer)) != -1) {
304 crc.update(buffer, 0, bytesRead);
305 }
306 bis.close();
307 // Reset to beginning of input stream
308 bis = new BufferedInputStream(
309 new FileInputStream(file));
310 ZipEntry entry = new ZipEntry(name);
311 entry.setMethod(ZipEntry.STORED);
312 entry.setCompressedSize(file.length());
313 entry.setSize(file.length());
314 entry.setCrc(crc.getValue());
315 zos.putNextEntry(entry);
316 while ((bytesRead = bis.read(buffer)) != -1) {
317 zos.write(buffer, 0, bytesRead);
318 }
319 bis.close();
320 }
321 zos.close();
322 }
323 }
324
325 //16. 解析/读取XML 文件
326 XML文件
327 <?xml version="1.0"?>
328 <students>
329 <student>
330 <name>John</name>
331 <grade>B</grade>
332 <age>12</age>
333 </student>
334 <student>
335 <name>Mary</name>
336 <grade>A</grade>
337 <age>11</age>
338 </student>
339 <student>
340 <name>Simon</name>
341 <grade>A</grade>
342 <age>18</age>
343 </student>
344 </students>
345
346 //Java代码
347 package net.viralpatel.java.xmlparser;
348
349 import java.io.File;
350 import javax.xml.parsers.DocumentBuilder;
351 import javax.xml.parsers.DocumentBuilderFactory;
352
353 import org.w3c.dom.Document;
354 import org.w3c.dom.Element;
355 import org.w3c.dom.Node;
356 import org.w3c.dom.NodeList;
357
358 public class XMLParser {
359
360 public void getAllUserNames(String fileName) {
361 try {
362 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
363 DocumentBuilder db = dbf.newDocumentBuilder();
364 File file = new File(fileName);
365 if (file.exists()) {
366 Document doc = db.parse(file);
367 Element docEle = doc.getDocumentElement();
368
369 // Print root element of the document
370 System.out.println("Root element of the document: "
371 + docEle.getNodeName());
372
373 NodeList studentList = docEle.getElementsByTagName("student");
374
375 // Print total student elements in document
376 System.out
377 .println("Total students: " + studentList.getLength());
378
379 if (studentList != null && studentList.getLength() > 0) {
380 for (int i = 0; i < studentList.getLength(); i++) {
381
382 Node node = studentList.item(i);
383
384 if (node.getNodeType() == Node.ELEMENT_NODE) {
385
386 System.out
387 .println("=====================");
388
389 Element e = (Element) node;
390 NodeList nodeList = e.getElementsByTagName("name");
391 System.out.println("Name: "
392 + nodeList.item(0).getChildNodes().item(0)
393 .getNodeValue());
394
395 nodeList = e.getElementsByTagName("grade");
396 System.out.println("Grade: "
397 + nodeList.item(0).getChildNodes().item(0)
398 .getNodeValue());
399
400 nodeList = e.getElementsByTagName("age");
401 System.out.println("Age: "
402 + nodeList.item(0).getChildNodes().item(0)
403 .getNodeValue());
404 }
405 }
406 } else {
407 System.exit(1);
408 }
409 }
410 } catch (Exception e) {
411 System.out.println(e);
412 }
413 }
414 public static void main(String[] args) {
415
416 XMLParser parser = new XMLParser();
417 parser.getAllUserNames("c:\\test.xml");
418 }
419 }
420 //17. 把 Array 转换成 Map
421 import java.util.Map;
422 import org.apache.commons.lang.ArrayUtils;
423
424 public class Main {
425
426 public static void main(String[] args) {
427 String[ ][ ] countries = { { "United States", "New York" }, { "United Kingdom", "London" },
428 { "Netherland", "Amsterdam" }, { "Japan", "Tokyo" }, { "France", "Paris" } };
429
430 Map countryCapitals = ArrayUtils.toMap(countries);
431
432 System.out.println("Capital of Japan is " + countryCapitals.get("Japan"));
433 System.out.println("Capital of France is " + countryCapitals.get("France"));
434 }
435 }
436
437 //18. 发送邮件
438 import javax.mail.*;
439 import javax.mail.internet.*;
440 import java.util.*;
441
442 public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException
443 {
444 boolean debug = false;
445
446 //Set the host smtp address
447 Properties props = new Properties();
448 props.put("mail.smtp.host", "smtp.example.com");
449
450 // create some properties and get the default Session
451 Session session = Session.getDefaultInstance(props, null);
452 session.setDebug(debug);
453
454 // create a message
455 Message msg = new MimeMessage(session);
456
457 // set the from and to address
458 InternetAddress addressFrom = new InternetAddress(from);
459 msg.setFrom(addressFrom);
460
461 InternetAddress[] addressTo = new InternetAddress[recipients.length];
462 for (int i = 0; i < recipients.length; i++)
463 {
464 addressTo[i] = new InternetAddress(recipients[i]);
465 }
466 msg.setRecipients(Message.RecipientType.TO, addressTo);
467
468 // Optional : You can also set your custom headers in the Email if you Want
469 msg.addHeader("MyHeaderName", "myHeaderValue");
470
471 // Setting the Subject and Content Type
472 msg.setSubject(subject);
473 msg.setContent(message, "text/plain");
474 Transport.send(msg);
475 }
476
477 //19. 发送代数据的HTTP 请求
478 import java.io.BufferedReader;
479 import java.io.InputStreamReader;
480 import java.net.URL;
481
482 public class Main {
483 public static void main(String[] args) {
484 try {
485 URL my_url = new URL("http://cocre.com/");
486 BufferedReader br = new BufferedReader(new InputStreamReader(my_url.openStream()));
487 String strTemp = "";
488 while(null != (strTemp = br.readLine())){
489 System.out.println(strTemp);
490 }
491 } catch (Exception ex) {
492 ex.printStackTrace();
493 }
494 }
495 }
496
497 //20. 改变数组的大小
498 /**
499 * Reallocates an array with a new size, and copies the contents
500 * of the old array to the new array.
501 * @param oldArray the old array, to be reallocated.
502 * @param newSize the new array size.
503 * @return A new array with the same contents.
504 */
505 private static Object resizeArray (Object oldArray, int newSize) {
506 int oldSize = java.lang.reflect.Array.getLength(oldArray);
507 Class elementType = oldArray.getClass().getComponentType();
508 Object newArray = java.lang.reflect.Array.newInstance(
509 elementType,newSize);
510 int preserveLength = Math.min(oldSize,newSize);
511 if (preserveLength > 0)
512 System.arraycopy (oldArray,0,newArray,0,preserveLength);
513 return newArray;
514 }
515
516 // Test routine for resizeArray().
517 public static void main (String[] args) {
518 int[] a = {1,2,3};
519 a = (int[])resizeArray(a,5);
520 a[3] = 4;
521 a[4] = 5;
522 for (int i=0; i<a.length; i++)
523 System.out.println (a[i]);
524 }
002 String a = String.valueOf(2); //integer to numeric string
003 int i = Integer.parseInt(a); //numeric string to an int
004
005 //2. 向文件末尾添加内容
006 BufferedWriter out = null;
007 try {
008 out = new BufferedWriter(new FileWriter(”filename”, true));
009 out.write(”aString”);
010 } catch (IOException e) {
011 // error processing code
012
013 } finally {
014 if (out != null) {
015 out.close();
016 }
017
018 }
019
020 //3. 得到当前方法的名字
021 String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
022
023 //4. 转字符串到日期
024 java.util.Date = java.text.DateFormat.getDateInstance().parse(date String);
025 //或者是:
026 SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );
027 Date date = format.parse( myString );
028
029 //5. 使用JDBC链接Oracle
030 public class OracleJdbcTest
031 {
032 String driverClass = "oracle.jdbc.driver.OracleDriver";
033
034 Connection con;
035
036 public void init(FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException
037 {
038 Properties props = new Properties();
039 props.load(fs);
040 String url = props.getProperty("db.url");
041 String userName = props.getProperty("db.user");
042 String password = props.getProperty("db.password");
043 Class.forName(driverClass);
044
045 con=DriverManager.getConnection(url, userName, password);
046 }
047
048 public void fetch() throws SQLException, IOException
049 {
050 PreparedStatement ps = con.prepareStatement("select SYSDATE from dual");
051 ResultSet rs = ps.executeQuery();
052
053 while (rs.next())
054 {
055 // do the thing you do
056 }
057 rs.close();
058 ps.close();
059 }
060
061 public static void main(String[] args)
062 {
063 OracleJdbcTest test = new OracleJdbcTest();
064 test.init();
065 test.fetch();
066 }
067 }
068
069 6. 把 Java util.Date 转成 sql.Date
070 java.util.Date utilDate = new java.util.Date();
071 java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
072
073 //7. 使用NIO进行快速的文件拷贝
074 public static void fileCopy( File in, File out )
075 throws IOException
076 {
077 FileChannel inChannel = new FileInputStream( in ).getChannel();
078 FileChannel outChannel = new FileOutputStream( out ).getChannel();
079 try
080 {
081 // inChannel.transferTo(0, inChannel.size(), outChannel); // original -- apparently has trouble copying large files on Windows
082
083 // magic number for Windows, 64Mb - 32Kb)
084 int maxCount = (64 * 1024 * 1024) - (32 * 1024);
085 long size = inChannel.size();
086 long position = 0;
087 while ( position < size )
088 {
089 position += inChannel.transferTo( position, maxCount, outChannel );
090 }
091 }
092 finally
093 {
094 if ( inChannel != null )
095 {
096 inChannel.close();
097 }
098 if ( outChannel != null )
099 {
100 outChannel.close();
101 }
102 }
103 }
104
105 //8. 创建图片的缩略图
106 private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename)
107 throws InterruptedException, FileNotFoundException, IOException
108 {
109 // load image from filename
110 Image image = Toolkit.getDefaultToolkit().getImage(filename);
111 MediaTracker mediaTracker = new MediaTracker(new Container());
112 mediaTracker.addImage(image, 0);
113 mediaTracker.waitForID(0);
114 // use this to test for errors at this point: System.out.println(mediaTracker.isErrorAny());
115
116 // determine thumbnail size from WIDTH and HEIGHT
117 double thumbRatio = (double)thumbWidth / (double)thumbHeight;
118 int imageWidth = image.getWidth(null);
119 int imageHeight = image.getHeight(null);
120 double imageRatio = (double)imageWidth / (double)imageHeight;
121 if (thumbRatio < imageRatio) {
122 thumbHeight = (int)(thumbWidth / imageRatio);
123 } else {
124 thumbWidth = (int)(thumbHeight * imageRatio);
125 }
126
127 // draw original image to thumbnail image object and
128 // scale it to the new size on-the-fly
129 BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
130 Graphics2D graphics2D = thumbImage.createGraphics();
131 graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
132 graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
133
134 // save thumbnail image to outFilename
135 BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename));
136 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
137 JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
138 quality = Math.max(0, Math.min(quality, 100));
139 param.setQuality((float)quality / 100.0f, false);
140 encoder.setJPEGEncodeParam(param);
141 encoder.encode(thumbImage);
142 out.close();
143 }
144
145 //9. 创建 JSON 格式的数据
146 import org.json.JSONObject;
147 ...
148 ...
149 JSONObject json = new JSONObject();
150 json.put("city", "Mumbai");
151 json.put("country", "India");
152 ...
153 String output = json.toString();
154 ...
155
156 //10. 使用iText JAR生成PDF
157 import java.io.File;
158 import java.io.FileOutputStream;
159 import java.io.OutputStream;
160 import java.util.Date;
161
162 import com.lowagie.text.Document;
163 import com.lowagie.text.Paragraph;
164 import com.lowagie.text.pdf.PdfWriter;
165
166 public class GeneratePDF {
167
168 public static void main(String[] args) {
169 try {
170 OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
171
172 Document document = new Document();
173 PdfWriter.getInstance(document, file);
174 document.open();
175 document.add(new Paragraph("Hello Kiran"));
176 document.add(new Paragraph(new Date().toString()));
177
178 document.close();
179 file.close();
180
181 } catch (Exception e) {
182
183 e.printStackTrace();
184 }
185 }
186 }
187
188 //11. HTTP 代理设置
189 System.getProperties().put("http.proxyHost", "someProxyURL");
190 System.getProperties().put("http.proxyPort", "someProxyPort");
191 System.getProperties().put("http.proxyUser", "someUserName");
192 System.getProperties().put("http.proxyPassword", "somePassword");
193
194 //12. 单实例Singleton 示例
195 public class SimpleSingleton {
196 private static SimpleSingleton singleInstance = new SimpleSingleton();
197
198 //Marking default constructor private
199 //to avoid direct instantiation.
200 private SimpleSingleton() {
201 }
202
203 //Get instance for class SimpleSingleton
204 public static SimpleSingleton getInstance() {
205
206 return singleInstance;
207 }
208 }
209
210 //另一种实现
211
212 public enum SimpleSingleton {
213 INSTANCE;
214 public void doSomething() {
215 }
216 }
217
218 //Call the method from Singleton:
219 SimpleSingleton.INSTANCE.doSomething();
220
221 //13. 抓屏程序
222 import java.awt.Dimension;
223 import java.awt.Rectangle;
224 import java.awt.Robot;
225 import java.awt.Toolkit;
226 import java.awt.image.BufferedImage;
227 import javax.imageio.ImageIO;
228 import java.io.File;
229
230 ...
231 public void captureScreen(String fileName) throws Exception {
232
233 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
234 Rectangle screenRectangle = new Rectangle(screenSize);
235 Robot robot = new Robot();
236 BufferedImage image = robot.createScreenCapture(screenRectangle);
237 ImageIO.write(image, "png", new File(fileName));
238
239 }
240 //14. 列出文件和目录
241 File dir = new File("directoryName");
242 String[] children = dir.list();
243 if (children == null) {
244 // Either dir does not exist or is not a directory
245 } else {
246 for (int i=0; i < children.length; i++) {
247 // Get filename of file or directory
248 String filename = children[i];
249 }
250 }
251
252 // It is also possible to filter the list of returned files.
253 // This example does not return any files that start with `.’.
254 FilenameFilter filter = new FilenameFilter() {
255 public boolean accept(File dir, String name) {
256 return !name.startsWith(".");
257 }
258 };
259 children = dir.list(filter);
260
261 // The list of files can also be retrieved as File objects
262 File[] files = dir.listFiles();
263
264 // This filter only returns directories
265 FileFilter fileFilter = new FileFilter() {
266 public boolean accept(File file) {
267 return file.isDirectory();
268 }
269 };
270 files = dir.listFiles(fileFilter);
271
272 //15. 创建ZIP和JAR文件
273
274 import java.util.zip.*;
275 import java.io.*;
276
277 public class ZipIt {
278 public static void main(String args[]) throws IOException {
279 if (args.length < 2) {
280 System.err.println("usage: java ZipIt Zip.zip file1 file2 file3");
281 System.exit(-1);
282 }
283 File zipFile = new File(args[0]);
284 if (zipFile.exists()) {
285 System.err.println("Zip file already exists, please try another");
286 System.exit(-2);
287 }
288 FileOutputStream fos = new FileOutputStream(zipFile);
289 ZipOutputStream zos = new ZipOutputStream(fos);
290 int bytesRead;
291 byte[] buffer = new byte[1024];
292 CRC32 crc = new CRC32();
293 for (int i=1, n=args.length; i < n; i++) {
294 String name = args[i];
295 File file = new File(name);
296 if (!file.exists()) {
297 System.err.println("Skipping: " + name);
298 continue;
299 }
300 BufferedInputStream bis = new BufferedInputStream(
301 new FileInputStream(file));
302 crc.reset();
303 while ((bytesRead = bis.read(buffer)) != -1) {
304 crc.update(buffer, 0, bytesRead);
305 }
306 bis.close();
307 // Reset to beginning of input stream
308 bis = new BufferedInputStream(
309 new FileInputStream(file));
310 ZipEntry entry = new ZipEntry(name);
311 entry.setMethod(ZipEntry.STORED);
312 entry.setCompressedSize(file.length());
313 entry.setSize(file.length());
314 entry.setCrc(crc.getValue());
315 zos.putNextEntry(entry);
316 while ((bytesRead = bis.read(buffer)) != -1) {
317 zos.write(buffer, 0, bytesRead);
318 }
319 bis.close();
320 }
321 zos.close();
322 }
323 }
324
325 //16. 解析/读取XML 文件
326 XML文件
327 <?xml version="1.0"?>
328 <students>
329 <student>
330 <name>John</name>
331 <grade>B</grade>
332 <age>12</age>
333 </student>
334 <student>
335 <name>Mary</name>
336 <grade>A</grade>
337 <age>11</age>
338 </student>
339 <student>
340 <name>Simon</name>
341 <grade>A</grade>
342 <age>18</age>
343 </student>
344 </students>
345
346 //Java代码
347 package net.viralpatel.java.xmlparser;
348
349 import java.io.File;
350 import javax.xml.parsers.DocumentBuilder;
351 import javax.xml.parsers.DocumentBuilderFactory;
352
353 import org.w3c.dom.Document;
354 import org.w3c.dom.Element;
355 import org.w3c.dom.Node;
356 import org.w3c.dom.NodeList;
357
358 public class XMLParser {
359
360 public void getAllUserNames(String fileName) {
361 try {
362 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
363 DocumentBuilder db = dbf.newDocumentBuilder();
364 File file = new File(fileName);
365 if (file.exists()) {
366 Document doc = db.parse(file);
367 Element docEle = doc.getDocumentElement();
368
369 // Print root element of the document
370 System.out.println("Root element of the document: "
371 + docEle.getNodeName());
372
373 NodeList studentList = docEle.getElementsByTagName("student");
374
375 // Print total student elements in document
376 System.out
377 .println("Total students: " + studentList.getLength());
378
379 if (studentList != null && studentList.getLength() > 0) {
380 for (int i = 0; i < studentList.getLength(); i++) {
381
382 Node node = studentList.item(i);
383
384 if (node.getNodeType() == Node.ELEMENT_NODE) {
385
386 System.out
387 .println("=====================");
388
389 Element e = (Element) node;
390 NodeList nodeList = e.getElementsByTagName("name");
391 System.out.println("Name: "
392 + nodeList.item(0).getChildNodes().item(0)
393 .getNodeValue());
394
395 nodeList = e.getElementsByTagName("grade");
396 System.out.println("Grade: "
397 + nodeList.item(0).getChildNodes().item(0)
398 .getNodeValue());
399
400 nodeList = e.getElementsByTagName("age");
401 System.out.println("Age: "
402 + nodeList.item(0).getChildNodes().item(0)
403 .getNodeValue());
404 }
405 }
406 } else {
407 System.exit(1);
408 }
409 }
410 } catch (Exception e) {
411 System.out.println(e);
412 }
413 }
414 public static void main(String[] args) {
415
416 XMLParser parser = new XMLParser();
417 parser.getAllUserNames("c:\\test.xml");
418 }
419 }
420 //17. 把 Array 转换成 Map
421 import java.util.Map;
422 import org.apache.commons.lang.ArrayUtils;
423
424 public class Main {
425
426 public static void main(String[] args) {
427 String[ ][ ] countries = { { "United States", "New York" }, { "United Kingdom", "London" },
428 { "Netherland", "Amsterdam" }, { "Japan", "Tokyo" }, { "France", "Paris" } };
429
430 Map countryCapitals = ArrayUtils.toMap(countries);
431
432 System.out.println("Capital of Japan is " + countryCapitals.get("Japan"));
433 System.out.println("Capital of France is " + countryCapitals.get("France"));
434 }
435 }
436
437 //18. 发送邮件
438 import javax.mail.*;
439 import javax.mail.internet.*;
440 import java.util.*;
441
442 public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException
443 {
444 boolean debug = false;
445
446 //Set the host smtp address
447 Properties props = new Properties();
448 props.put("mail.smtp.host", "smtp.example.com");
449
450 // create some properties and get the default Session
451 Session session = Session.getDefaultInstance(props, null);
452 session.setDebug(debug);
453
454 // create a message
455 Message msg = new MimeMessage(session);
456
457 // set the from and to address
458 InternetAddress addressFrom = new InternetAddress(from);
459 msg.setFrom(addressFrom);
460
461 InternetAddress[] addressTo = new InternetAddress[recipients.length];
462 for (int i = 0; i < recipients.length; i++)
463 {
464 addressTo[i] = new InternetAddress(recipients[i]);
465 }
466 msg.setRecipients(Message.RecipientType.TO, addressTo);
467
468 // Optional : You can also set your custom headers in the Email if you Want
469 msg.addHeader("MyHeaderName", "myHeaderValue");
470
471 // Setting the Subject and Content Type
472 msg.setSubject(subject);
473 msg.setContent(message, "text/plain");
474 Transport.send(msg);
475 }
476
477 //19. 发送代数据的HTTP 请求
478 import java.io.BufferedReader;
479 import java.io.InputStreamReader;
480 import java.net.URL;
481
482 public class Main {
483 public static void main(String[] args) {
484 try {
485 URL my_url = new URL("http://cocre.com/");
486 BufferedReader br = new BufferedReader(new InputStreamReader(my_url.openStream()));
487 String strTemp = "";
488 while(null != (strTemp = br.readLine())){
489 System.out.println(strTemp);
490 }
491 } catch (Exception ex) {
492 ex.printStackTrace();
493 }
494 }
495 }
496
497 //20. 改变数组的大小
498 /**
499 * Reallocates an array with a new size, and copies the contents
500 * of the old array to the new array.
501 * @param oldArray the old array, to be reallocated.
502 * @param newSize the new array size.
503 * @return A new array with the same contents.
504 */
505 private static Object resizeArray (Object oldArray, int newSize) {
506 int oldSize = java.lang.reflect.Array.getLength(oldArray);
507 Class elementType = oldArray.getClass().getComponentType();
508 Object newArray = java.lang.reflect.Array.newInstance(
509 elementType,newSize);
510 int preserveLength = Math.min(oldSize,newSize);
511 if (preserveLength > 0)
512 System.arraycopy (oldArray,0,newArray,0,preserveLength);
513 return newArray;
514 }
515
516 // Test routine for resizeArray().
517 public static void main (String[] args) {
518 int[] a = {1,2,3};
519 a = (int[])resizeArray(a,5);
520 a[3] = 4;
521 a[4] = 5;
522 for (int i=0; i<a.length; i++)
523 System.out.println (a[i]);
524 }
相关推荐
Java开发是一种广泛使用的编程语言,尤其在企业级应用和服务器端开发中占据重要地位。对于初学者或希望转行到Java开发的人来说,了解并掌握以下关键技术和概念是至关重要的。 1. **Java基础**:首先,你需要理解...
在Java开发中,以下是一些常用API的知识点: 1. **集合框架**:Java集合框架是处理对象集合的一系列接口和类,包括List(如ArrayList和LinkedList)、Set(如HashSet和TreeSet)和Map(如HashMap和TreeMap)。这些...
《Java开发实战经典》这本书是Java开发者的重要参考资料,它涵盖了Java编程语言的核心技术和实践应用。以下将详细解析这本书可能涉及的知识点。 1. **Java基础知识**:书中首先会介绍Java的基础概念,包括Java的...
手册分为五大块:编程规约、异常日志、MySQL数据库、工程结构、安全规约,涵盖了Java开发中的各个方面。 编程规约 编程规约是Java开发手册的核心部分,旨在规范Java开发者的编程风格和编码习惯。编程规约包括命名...
Java开发资源库是一个全面的学习平台,专为Java初学者和有经验的开发者提供从入门到精通的全方位指导。这个资源库包含了大量的实例和项目,帮助用户深入理解和实践Java编程语言的核心概念和技术。以下是对资源库中...
虽然描述中提到的是一个简洁的20字概述,但我们可以深入探讨Java开发的一些关键知识点。 首先,Java是一种面向对象的编程语言,它的设计目标是具有平台无关性,这意味着编写在一种平台上运行的Java程序可以无需修改...
这份手册深入浅出地介绍了唯品会在Java开发过程中的最佳实践、规范以及常用工具。其中,VJTools-master作为压缩包内的一个子文件,很可能是唯品会内部开发的一套工具集或框架,用于提升开发效率和代码质量。 Java是...
HelloWorldApp.java 第一个用Java开发的应用程序。 firstApplet.java 第一个用Java开发的Applet小程序。 firstApplet.htm 用来装载Applet的网页文件 第2章 示例描述:本章介绍开发Java的基础语法知识。 ...
8. **数据库操作**:使用JDBC(Java Database Connectivity)进行数据库操作是Java开发中常见的任务。实例将展示如何连接数据库、执行SQL查询、处理结果集等。 9. **GUI编程**:Java的Swing和JavaFX库可以构建图形...
Java编程开发入门是初学者踏入计算机编程领域的重要一课,特别是在企业级应用开发中,Java因其强大、稳定和跨平台的特性,成为了许多开发者首选的语言。这份资料旨在为初学者提供一个全面的学习路径,帮助他们理解和...
这份"java后端开发规范word文档"包含了多个方面的内容,包括但不限于编程风格、命名规则、异常处理、并发控制、数据库操作、单元测试、日志记录以及代码组织结构等。 1. **编程风格**:编程风格是代码可读性的基础...
Java开发类库是Java编程中不可或缺的一部分,它们提供了一系列预定义的函数和对象,帮助开发者高效地编写代码,实现各种功能。"通用Java开发类库"通常指的是那些广泛适用、可复用性强的基础工具类库,可以应用于各种...
《Java开发实战1200例(第1卷)》是一部深入浅出的Java编程教程,旨在通过大量的实例,帮助读者掌握Java编程的核心技术和实践应用。本书覆盖了Java语言的基础到高级特性,包括面向对象编程、类库使用、异常处理、多...
《JAVA开发技术大全》是由知名讲师刘新老师编写的,是一部深入浅出的JAVA基础教程。本书涵盖了JAVA语言的核心概念、语法结构以及实际应用,旨在为初学者提供全面且系统的JAVA学习路径,同时也适合有一定经验的开发者...
【标题】:“基于Java开发的通讯录软件” 在IT领域,Java是一种广泛应用的编程语言,以其跨平台性、面向对象的特性以及丰富的类库而受到开发者喜爱。本项目是广东一所211大学的学生在学习Java后进行的课程设计,其...
【Java开发基础】 Java是一种广泛使用的面向对象的编程语言,具有平台独立性、安全性和高性能的特点。在Java开发过程中,通常需要安装Java开发环境,包括JDK(Java Development Kit),它包含了Java编译器、Java运行...
《JAVA开发实战经典》是由知名IT教育专家李兴华老师编撰的一套全面而深入的Java编程教程。这套PPT涵盖了Java开发的各个方面,旨在帮助初学者和有经验的开发者提升技能,掌握Java核心技术,实现从理论到实践的飞跃。 ...
10. **Java框架**:Spring、MyBatis、Hibernate等是Java开发中常用的框架,它们简化了开发过程并提供了许多功能,如依赖注入、数据库操作和事务管理。 "example2"可能是一个包含上述某个或多个知识点的实际代码示例...
以上知识点详细阐述了《java开发实战经典》第二版中李兴华提供的课后习题答案所涉及的Java编程基础内容,覆盖了Java语言的核心概念和编程实践。这些知识点不仅适用于理解书本上的习题答案,而且对于深入学习Java语言...