`

20非常有用的Java程序片段 (中)

    博客分类:
  • J2SE
阅读更多

12. 单实例Singleton 示例

请先阅读这篇文章 了解更多信息

view source
<embed id="highlighter_35199_clipboard" title="copy to clipboard" type="application/x-shockwave-flash" width="16" height="16" src="http://cocre.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter/scripts/clipboard.swf" lk_media="yes" lk_mediaid="lk_juiceapp_mediaPopup_1243315889019" allowscriptaccess="always" wmode="transparent" flashvars="highlighterId=highlighter_35199" menu="false"></embed>
print ?
01.    
02. public class SimpleSingleton {  
03.      private static SimpleSingleton singleInstance =  new SimpleSingleton();  
04.    
05.      //Marking default constructor private  
06.      //to avoid direct instantiation.  
07.      private SimpleSingleton() {  
08.      }  
09.    
10.      //Get instance for class SimpleSingleton  
11.      public static SimpleSingleton getInstance() {  
12.    
13.          return singleInstance;  
14.      }  
15.

另一种实现

view source
<embed id="highlighter_120550_clipboard" title="copy to clipboard" type="application/x-shockwave-flash" width="16" height="16" src="http://cocre.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter/scripts/clipboard.swf" lk_media="yes" lk_mediaid="lk_juiceapp_mediaPopup_1243315889023" allowscriptaccess="always" wmode="transparent" flashvars="highlighterId=highlighter_120550" menu="false"></embed>
print ?
1. public enum SimpleSingleton {  
2.      INSTANCE;  
3.      public void doSomething() {  
4.      }  
5. }  
6.    
7. //Call the method from Singleton:  
8. SimpleSingleton.INSTANCE.doSomething(); 

13. 抓屏程序

阅读这篇文章 获得更多信息。

view source
<embed id="highlighter_817602_clipboard" title="copy to clipboard" type="application/x-shockwave-flash" width="16" height="16" src="http://cocre.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter/scripts/clipboard.swf" lk_media="yes" lk_mediaid="lk_juiceapp_mediaPopup_1243315889027" allowscriptaccess="always" wmode="transparent" flashvars="highlighterId=highlighter_817602" menu="false"></embed>
print ?
01. import java.awt.Dimension;  
02. import java.awt.Rectangle;  
03. import java.awt.Robot;  
04. import java.awt.Toolkit;  
05. import java.awt.image.BufferedImage;  
06. import javax.imageio.ImageIO;  
07. import java.io.File;  
08.    
09. ...  
10.    
11. public void captureScreen(String fileName) throws Exception {  
12.    
13.     Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();  
14.     Rectangle screenRectangle = new Rectangle(screenSize);  
15.     Robot robot = new Robot();  
16.     BufferedImage image = robot.createScreenCapture(screenRectangle);  
17.     ImageIO.write(image, "png" , new File(fileName));  
18.    
19. }  
20. ... 

 

 

14. 列出文件和目录

view source
<embed id="highlighter_1356_clipboard" title="copy to clipboard" type="application/x-shockwave-flash" width="16" height="16" src="http://cocre.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter/scripts/clipboard.swf" lk_media="yes" lk_mediaid="lk_juiceapp_mediaPopup_1243315889031" allowscriptaccess="always" wmode="transparent" flashvars="highlighterId=highlighter_1356" menu="false"></embed>
print ?
01. File dir = new File( "directoryName" );  
02.    String[] children = dir.list();  
03.    if (children == null ) {  
04.        // Either dir does not exist or is not a directory  
05.    } else {  
06.        for ( int i= 0 ; i < children.length; i++) {  
07.            // Get filename of file or directory  
08.            String filename = children[i];  
09.        }  
10.    }  
11.    
12.    // It is also possible to filter the list of returned files.  
13.    // This example does not return any files that start with `.'.  
14.    FilenameFilter filter = new FilenameFilter() {  
15.        public boolean accept(File dir, String name) {  
16.            return !name.startsWith( "." );  
17.        }  
18.    };  
19.    children = dir.list(filter);  
20.    
21.    // The list of files can also be retrieved as File objects  
22.    File[] files = dir.listFiles();  
23.    
24.    // This filter only returns directories  
25.    FileFilter fileFilter = new FileFilter() {  
26.        public boolean accept(File file) {  
27.            return file.isDirectory();  
28.        }  
29.    };  
30.    files = dir.listFiles(fileFilter); 

15. 创建ZIP和JAR文件

view source
<embed id="highlighter_695137_clipboard" title="copy to clipboard" type="application/x-shockwave-flash" width="16" height="16" src="http://cocre.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter/scripts/clipboard.swf" lk_media="yes" lk_mediaid="lk_juiceapp_mediaPopup_1243315889035" allowscriptaccess="always" wmode="transparent" flashvars="highlighterId=highlighter_695137" menu="false"></embed>
print ?
01.    
02. import java.util.zip.*;  
03. import java.io.*;  
04.    
05. public class ZipIt {  
06.      public static void main(String args[]) throws IOException {  
07.          if (args.length < 2 ) {  
08.              System.err.println( "usage: java ZipIt Zip.zip file1 file2 file3" );  
09.              System.exit(- 1 );  
10.          }  
11.          File zipFile = new File(args[ 0 ]);  
12.          if (zipFile.exists()) {  
13.              System.err.println( "Zip file already exists, please try another" );  
14.              System.exit(- 2 );  
15.          }  
16.          FileOutputStream fos = new FileOutputStream(zipFile);  
17.          ZipOutputStream zos = new ZipOutputStream(fos);  
18.          int bytesRead;  
19.          byte [] buffer = new byte [ 1024 ];  
20.          CRC32 crc = new CRC32();  
21.          for ( int i= 1 , n=args.length; i < n; i++) {  
22.              String name = args[i];  
23.              File file = new File(name);  
24.              if (!file.exists()) {  
25.                  System.err.println( "Skipping: " + name);  
26.                  continue ;  
27.              }  
28.              BufferedInputStream bis = new BufferedInputStream(  
29.                  new FileInputStream(file));  
30.              crc.reset();  
31.              while ((bytesRead = bis.read(buffer)) != - 1 ) {  
32.                  crc.update(buffer, 0 , bytesRead);  
33.              }  
34.              bis.close();  
35.              // Reset to beginning of input stream  
36.              bis = new BufferedInputStream(  
37.                  new FileInputStream(file));  
38.              ZipEntry entry = new ZipEntry(name);  
39.              entry.setMethod(ZipEntry.STORED);  
40.              entry.setCompressedSize(file.length());  
41.              entry.setSize(file.length());  
42.              entry.setCrc(crc.getValue());  
43.              zos.putNextEntry(entry);  
44.              while ((bytesRead = bis.read(buffer)) != - 1 ) {  
45.                  zos.write(buffer, 0 , bytesRead);  
46.              }  
47.              bis.close();  
48.          }  
49.          zos.close();  
50.      }  
51.

16. 解析/读取XML 文件

XML文件

view source
<embed id="highlighter_879090_clipboard" title="copy to clipboard" type="application/x-shockwave-flash" width="16" height="16" src="http://cocre.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter/scripts/clipboard.swf" lk_media="yes" lk_mediaid="lk_juiceapp_mediaPopup_1243315889039" allowscriptaccess="always" wmode="transparent" flashvars="highlighterId=highlighter_879090" menu="false"></embed>
print ?
01. <? xml version = "1.0" ?> 
02. < students
03.      < student
04.          < name >John</ name
05.          < grade >B</ grade
06.          < age >12</ age
07.      </ student
08.      < student
09.          < name >Mary</ name
10.          < grade >A</ grade
11.          < age >11</ age
12.      </ student
13.      < student
14.          < name >Simon</ name
15.          < grade >A</ grade
16.          < age >18</ age
17.      </ student
18. </ students

Java代码

view source
<embed id="highlighter_40476_clipboard" title="copy to clipboard" type="application/x-shockwave-flash" width="16" height="16" src="http://cocre.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter/scripts/clipboard.swf" lk_media="yes" lk_mediaid="lk_juiceapp_mediaPopup_1243315889043" allowscriptaccess="always" wmode="transparent" flashvars="highlighterId=highlighter_40476" menu="false"></embed>
print ?
01.    
02. package net.viralpatel.java.xmlparser;  
03.    
04. import java.io.File;  
05. import javax.xml.parsers.DocumentBuilder;  
06. import javax.xml.parsers.DocumentBuilderFactory;  
07.    
08. import org.w3c.dom.Document;  
09. import org.w3c.dom.Element;  
10. import org.w3c.dom.Node;  
11. import org.w3c.dom.NodeList;  
12.    
13. public class XMLParser {  
14.    
15.      public void getAllUserNames(String fileName) {  
16.          try {  
17.              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
18.              DocumentBuilder db = dbf.newDocumentBuilder();  
19.              File file = new File(fileName);  
20.              if (file.exists()) {  
21.                  Document doc = db.parse(file);  
22.                  Element docEle = doc.getDocumentElement();  
23.    
24.                  // Print root element of the document  
25.                  System.out.println( "Root element of the document: "  
26.                          + docEle.getNodeName());  
27.    
28.                  NodeList studentList = docEle.getElementsByTagName( "student" );  
29.    
30.                  // Print total student elements in document  
31.                  System.out  
32.                          .println( "Total students: " + studentList.getLength());  
33.    
34.                  if (studentList != null && studentList.getLength() > 0 ) {  
35.                      for ( int i = 0 ; i < studentList.getLength(); i++) {  
36.    
37.                          Node node = studentList.item(i);  
38.    
39.                          if (node.getNodeType() == Node.ELEMENT_NODE) {  
40.    
41.                              System.out  
42.                                      .println( "=====================" );  
43.    
44.                              Element e = (Element) node;  
45.                              NodeList nodeList = e.getElementsByTagName( "name" );  
46.                              System.out.println( "Name: "  
47.                                      + nodeList.item( 0 ).getChildNodes().item( 0 )  
48.                                              .getNodeValue());  
49.    
50.                              nodeList = e.getElementsByTagName( "grade" );  
51.                              System.out.println( "Grade: "  
52.                                      + nodeList.item( 0 ).getChildNodes().item( 0 )  
53.                                              .getNodeValue());  
54.    
55.                              nodeList = e.getElementsByTagName( "age" );  
56.                              System.out.println( "Age: "  
57.                                      + nodeList.item( 0 ).getChildNodes().item( 0 )  
58.                                              .getNodeValue());  
59.                          }  
60.                      }  
61.                  } else {  
62.                      System.exit( 1 );  
63.                  }  
64.              }  
65.          } catch (Exception e) {  
66.              System.out.println(e);  
67.          }  
68.      }  
69.      public static void main(String[] args) {  
70.    
71.          XMLParser parser = new XMLParser();  
72.          parser.getAllUserNames( "c:\\test.xml" );  
73.      }  
74.

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics