20 very useful java program fragments — to

Original address: http://geek.csdn.net/news/detail/236591

Here are 20 very useful java program fragments. I hope they can be useful to you.

1. Strings have integer conversion

2. Add content to the end of the document

3. Get the name of the current method

4. Transfer string to date

Or:

5. Use JDBC to link Oracle

Connection con;  

<span class="hljs-keyword"&gt;public <span class="hljs-keyword"&gt;void <span class="hljs-title"&gt;init(FileInputStream fs) <span class="hljs-keyword"&gt;throws ClassNotFoundException,<a href="https://www.jb51.cc/tag/sql/" target="_blank" class="keywords">sql</a>Exception,FileNotFoundException,IOException  
{  
    Properties props = <span class="hljs-keyword"&gt;new Properties();  
    props.load(fs);  
    String url = props.getProperty(<span class="hljs-string"&gt;"db.url");  
    String userName = props.getProperty(<span class="hljs-string"&gt;"db.user");  
    String password = props.getProperty(<span class="hljs-string"&gt;"db.password");  
    Class.forName(driverClass);  

    con=DriverManager.getConnection(url,userName,password);  
}  

<span class="hljs-keyword"&gt;public <span class="hljs-keyword"&gt;void <span class="hljs-title"&gt;fetch() <span class="hljs-keyword"&gt;throws <a href="https://www.jb51.cc/tag/sql/" target="_blank" class="keywords">sql</a>Exception,IOException  
{  
    PreparedStatement ps = con.prepareStatement(<span class="hljs-string"&gt;"select SYSDATE from dual");  
    ResultSet rs = ps.executeQuery();  

    <span class="hljs-keyword"&gt;while (rs.next())  
    {  
        <span class="hljs-comment"&gt;// do the thing you do  
    }  
    rs.close();  
    ps.close();  
}  

<span class="hljs-keyword"&gt;public <span class="hljs-keyword"&gt;static <span class="hljs-keyword"&gt;void <span class="hljs-title"&gt;main(String[] args)  
{  
    OracleJdbcTest test = <span class="hljs-keyword"&gt;new OracleJdbc<a href="https://www.jb51.cc/tag/test/" target="_blank" class="keywords">test()</a>;  
    test.init();  
    test.fetch();  
}  

}

6. Put Java util Convert date to SQL Date

7. Use NiO for fast file copying

        <span class="hljs-comment"&gt;// magic number for Windows,64Mb - 32Kb)  
        <span class="hljs-keyword"&gt;int maxCount = (<span class="hljs-number"&gt;64 * <span class="hljs-number"&gt;1024 * <span class="hljs-number"&gt;1024) - (<span class="hljs-number"&gt;32 * <span class="hljs-number"&gt;1024);  
        <span class="hljs-keyword"&gt;long size = inChannel.size();  
        <span class="hljs-keyword"&gt;long position = <span class="hljs-number"&gt;0;  
        <span class="hljs-keyword"&gt;while ( position < size )  
        {  
           position += inChannel.transferTo( position,maxCount,outChannel );  
        }  
    }  
    <span class="hljs-keyword"&gt;finally 
    {  
        <span class="hljs-keyword"&gt;if ( inChannel != <span class="hljs-keyword"&gt;null )  
        {  
           inChannel.close();  
        }  
        <span class="hljs-keyword"&gt;if ( outChannel != <span class="hljs-keyword"&gt;null )  
        {  
            outChannel.close();  
        }  
    }  
}</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></pre>

8. Create thumbnails of pictures

    <span class="hljs-comment"&gt;// deter<a href="https://www.jb51.cc/tag/mine/" target="_blank" class="keywords">mine</a> thumbnail size from WIDTH and HEIGHT  
    <span class="hljs-keyword"&gt;double thumbRatio = (<span class="hljs-keyword"&gt;double)thumbWidth / (<span class="hljs-keyword"&gt;double)thumbHeight;  
    <span class="hljs-keyword"&gt;int imageWidth = image.getWidth(<span class="hljs-keyword"&gt;null);  
    <span class="hljs-keyword"&gt;int imageHeight = image.getHeight(<span class="hljs-keyword"&gt;null);  
    <span class="hljs-keyword"&gt;double imageRatio = (<span class="hljs-keyword"&gt;double)imageWidth / (<span class="hljs-keyword"&gt;double)imageHeight;  
    <span class="hljs-keyword"&gt;if (thumbRatio < imageRatio) {  
        thumbHeight = (<span class="hljs-keyword"&gt;int)(thumbWidth / imageRatio);  
    } <span class="hljs-keyword"&gt;else {  
        thumbWidth = (<span class="hljs-keyword"&gt;int)(thumbHeight * imageRatio);  
    }  

    <span class="hljs-comment"&gt;// draw original image to thumbnail image object and  
    <span class="hljs-comment"&gt;// scale it to the new size on-the-fly  
    BufferedImage thumbImage = <span class="hljs-keyword"&gt;new BufferedImage(thumbWidth,thumbHeight,BufferedImage.TYPE_INT_RGB);  
    Graphics2D graphics2D = thumbImage.createGraphics();  
    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);  
    graphics2D.drawImage(image,<span class="hljs-number"&gt;0,thumbWidth,<span class="hljs-keyword"&gt;null);  

    <span class="hljs-comment"&gt;// save thumbnail image to outFilename  
    <a href="https://www.jb51.cc/tag/bufferedoutputstream/" target="_blank" class="keywords">bufferedoutputstream</a> <span class="hljs-keyword"&gt;out = <span class="hljs-keyword"&gt;new <a href="https://www.jb51.cc/tag/bufferedoutputstream/" target="_blank" class="keywords">bufferedoutputstream</a>(<span class="hljs-keyword"&gt;new FileOutputStream(outFilename));  
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(<span class="hljs-keyword"&gt;out);  
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);  
    quality = Math.max(<span class="hljs-number"&gt;0,Math.min(quality,<span class="hljs-number"&gt;100));  
    param.setQuality((<span class="hljs-keyword"&gt;float)quality / <span class="hljs-number"&gt;100.0f,<span class="hljs-keyword"&gt;false);  
    encoder.setJPEGEncodeParam(param);  
    encoder.encode(thumbImage);  
    <span class="hljs-keyword"&gt;out.close();  
}</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></pre>

9. Create data in JSON format

Please read for some details and the following jar file:

10. Generate PDF using iText jar

Read this article for more details

<span class="hljs-keyword">import com.lowagie.text.Document;
<span class="hljs-keyword">import com.lowagie.text.Paragraph;
<span class="hljs-keyword">import com.lowagie.text.pdf.PdfWriter;

<span class="hljs-javadoc">/**

  • Java学习交流QQ群:589809992 我们一起学Java!
    */

<span class="hljs-keyword">public <span class="hljs-class"><span class="hljs-keyword">class <span class="hljs-title">GeneratePDF {

<span class="hljs-keyword"&gt;public <span class="hljs-keyword"&gt;static <span class="hljs-keyword"&gt;void <span class="hljs-title"&gt;main(String[] args) {  
    <span class="hljs-keyword"&gt;try {  
        OutputStream file = <span class="hljs-keyword"&gt;new FileOutputStream(<span class="hljs-keyword"&gt;new File(<span class="hljs-string"&gt;"C:\\Test.pdf"));  

        Document document = <span class="hljs-keyword"&gt;new Document();  
        PdfWriter.getInstance(document,file);  
        document.open();  
        document.add(<span class="hljs-keyword"&gt;new Paragraph(<span class="hljs-string"&gt;"Hello Kiran"));  
        document.add(<span class="hljs-keyword"&gt;new Paragraph(<span class="hljs-keyword"&gt;new Date().toString()));  

        document.close();  
        file.close();  

    } <span class="hljs-keyword"&gt;catch (Exception e) {  

        e.printStackTrace();  
    }  
}  

}

11. HTTP proxy settings

Read this article for more details.

12. Single instance singleton example

Please read this article first for more information

<span class="hljs-comment"&gt;//Marking default constructor private  
<span class="hljs-comment"&gt;//to avoid direct instantiation.  
<span class="hljs-keyword"&gt;private <span class="hljs-title"&gt;SimpleSingleton() {  
}  

<span class="hljs-comment"&gt;//Get instance for class SimpleSingleton  
<span class="hljs-keyword"&gt;public <span class="hljs-keyword"&gt;static SimpleSingleton <span class="hljs-title"&gt;getInstance() {  

    <span class="hljs-keyword"&gt;return singleInstance;  
}  

}

Another implementation

<span class="hljs-comment">//Call the method from Singleton:
SimpleSingleton.INSTANCE.doSomething();

13. Screen capture program

Read this article for more information.

<span class="hljs-keyword">...  

public void captureScreen(String fileName) throws Exception {

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
ImageIO.write(image,<span class="hljs-string">"png",new File(fileName));

}
<span class="hljs-keyword">...

14. List files and directories

<span class="hljs-comment">// It is also possible to filter the list of returned files.
<span class="hljs-comment">// This example does not return any files that start with `.'.
FilenameFilter filter = <span class="hljs-keyword">new FilenameFilter() {
<span class="hljs-keyword">public <span class="hljs-keyword">boolean <span class="hljs-title">accept(File dir,String name) {
<span class="hljs-keyword">return !name.startsWith(<span class="hljs-string">".");
}
};
children = dir.list(filter);

<span class="hljs-comment">// The list of files can also be retrieved as File objects
File[] files = dir.listFiles();

<span class="hljs-comment">// This filter only returns directories
FileFilter fileFilter = <span class="hljs-keyword">new FileFilter() {
<span class="hljs-keyword">public <span class="hljs-keyword">boolean <span class="hljs-title">accept(File file) {
<span class="hljs-keyword">return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);

15. Create zip and jar files

< n; i++) { string name="args[i];" file file(name); >if (!file.exists()) system.err.println(

16. Parsing / reading XML files

XML file

 
 
     
        John 
        B 12   Mary A 11   Simon A 18  

Java code

import java<span class="hljs-preprocessor">.io<span class="hljs-preprocessor">.File<span class="hljs-comment">;
import javax<span class="hljs-preprocessor">.xml<span class="hljs-preprocessor">.parsers<span class="hljs-preprocessor">.DocumentBuilder<span class="hljs-comment">;
import javax<span class="hljs-preprocessor">.xml<span class="hljs-preprocessor">.parsers<span class="hljs-preprocessor">.DocumentBuilderFactory<span class="hljs-comment">;

import org<span class="hljs-preprocessor">.w3c<span class="hljs-preprocessor">.dom<span class="hljs-preprocessor">.Document<span class="hljs-comment">;
import org<span class="hljs-preprocessor">.w3c<span class="hljs-preprocessor">.dom<span class="hljs-preprocessor">.Element<span class="hljs-comment">;
import org<span class="hljs-preprocessor">.w3c<span class="hljs-preprocessor">.dom<span class="hljs-preprocessor">.Node<span class="hljs-comment">;
import org<span class="hljs-preprocessor">.w3c<span class="hljs-preprocessor">.dom<span class="hljs-preprocessor">.NodeList<span class="hljs-comment">;

public class XMLParser {

public void getAllUserNames(String fileName) {  
    try {  
        DocumentBuilderFactory dbf = DocumentBuilderFactory<span class="hljs-preprocessor"&gt;.newInstance()<span class="hljs-comment"&gt;;  
        DocumentBuilder db = dbf<span class="hljs-preprocessor"&gt;.newDocumentBuilder()<span class="hljs-comment"&gt;;  
        File file = new File(fileName)<span class="hljs-comment"&gt;;  
        if (file<span class="hljs-preprocessor"&gt;.exists()) {  
            Document doc = db<span class="hljs-preprocessor"&gt;.parse(file)<span class="hljs-comment"&gt;;  
            Element docEle = doc<span class="hljs-preprocessor"&gt;.getDocumentElement()<span class="hljs-comment"&gt;;  

            // Print root element of the document  
            Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a><span class="hljs-preprocessor"&gt;.out<span class="hljs-preprocessor"&gt;.println(<span class="hljs-string"&gt;"Root element of the document: " 
                    + docEle<span class="hljs-preprocessor"&gt;.getNodeName())<span class="hljs-comment"&gt;;  

            NodeList studentList = docEle<span class="hljs-preprocessor"&gt;.getElementsByTagName(<span class="hljs-string"&gt;"student")<span class="hljs-comment"&gt;;  

            // Print total student elements <span class="hljs-keyword"&gt;in document  
            Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a><span class="hljs-preprocessor"&gt;.out  
                    <span class="hljs-preprocessor"&gt;.println(<span class="hljs-string"&gt;"Total students: " + studentList<span class="hljs-preprocessor"&gt;.getLength())<span class="hljs-comment"&gt;;  

            if (studentList != null &amp;&amp; studentList<span class="hljs-preprocessor"&gt;.getLength() > <span class="hljs-number"&gt;0) {  
                for (int i = <span class="hljs-number"&gt;0<span class="hljs-comment"&gt;; i < studentList.getLength(); i++) {  

                    Node node = studentList<span class="hljs-preprocessor"&gt;.item(i)<span class="hljs-comment"&gt;;  

                    if (node<span class="hljs-preprocessor"&gt;.getNodeType() == Node<span class="hljs-preprocessor"&gt;.ELEMENT_NODE) {  

                        Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a><span class="hljs-preprocessor"&gt;.out  
                                <span class="hljs-preprocessor"&gt;.println(<span class="hljs-string"&gt;"=====================")<span class="hljs-comment"&gt;;  

                        Element e = (Element) node<span class="hljs-comment"&gt;;  
                        NodeList nodeList = e<span class="hljs-preprocessor"&gt;.getElementsByTagName(<span class="hljs-string"&gt;"name")<span class="hljs-comment"&gt;;  
                        Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a><span class="hljs-preprocessor"&gt;.out<span class="hljs-preprocessor"&gt;.println(<span class="hljs-string"&gt;"Name: " 
                                + nodeList<span class="hljs-preprocessor"&gt;.item(<span class="hljs-number"&gt;0)<span class="hljs-preprocessor"&gt;.getChildNodes()<span class="hljs-preprocessor"&gt;.item(<span class="hljs-number"&gt;0)  
                                        <span class="hljs-preprocessor"&gt;.getNodeValue())<span class="hljs-comment"&gt;;  

                        nodeList = e<span class="hljs-preprocessor"&gt;.getElementsByTagName(<span class="hljs-string"&gt;"grade")<span class="hljs-comment"&gt;;  
                        Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a><span class="hljs-preprocessor"&gt;.out<span class="hljs-preprocessor"&gt;.println(<span class="hljs-string"&gt;"Grade: " 
                                + nodeList<span class="hljs-preprocessor"&gt;.item(<span class="hljs-number"&gt;0)<span class="hljs-preprocessor"&gt;.getChildNodes()<span class="hljs-preprocessor"&gt;.item(<span class="hljs-number"&gt;0)  
                                        <span class="hljs-preprocessor"&gt;.getNodeValue())<span class="hljs-comment"&gt;;  

                        nodeList = e<span class="hljs-preprocessor"&gt;.getElementsByTagName(<span class="hljs-string"&gt;"age")<span class="hljs-comment"&gt;;  
                        Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a><span class="hljs-preprocessor"&gt;.out<span class="hljs-preprocessor"&gt;.println(<span class="hljs-string"&gt;"Age: " 
                                + nodeList<span class="hljs-preprocessor"&gt;.item(<span class="hljs-number"&gt;0)<span class="hljs-preprocessor"&gt;.getChildNodes()<span class="hljs-preprocessor"&gt;.item(<span class="hljs-number"&gt;0)  
                                        <span class="hljs-preprocessor"&gt;.getNodeValue())<span class="hljs-comment"&gt;;  
                    }  
                }  
            } else {  
                Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a><span class="hljs-preprocessor"&gt;.exit(<span class="hljs-number"&gt;1)<span class="hljs-comment"&gt;;  
            }  
        }  
    } catch (Exception e) {  
        Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a><span class="hljs-preprocessor"&gt;.out<span class="hljs-preprocessor"&gt;.println(e)<span class="hljs-comment"&gt;;  
    }  
}  
public static void main(String[] args) {  

    XMLParser parser = new XMLParser()<span class="hljs-comment"&gt;;  
    parser<span class="hljs-preprocessor"&gt;.getAllUserNames(<span class="hljs-string"&gt;"c:\\test.xml")<span class="hljs-comment"&gt;;  
}  

}

17. Convert array to map

<span class="hljs-keyword">public <span class="hljs-keyword">class Main {  

<span class="hljs-keyword">public <span class="hljs-keyword">static <span class="hljs-keyword">void <span class="hljs-title">main(String[] args) {
String[][] countries = { { <span class="hljs-string">"United States",<span class="hljs-string">"New York" },{ <span class="hljs-string">"United Kingdom",<span class="hljs-string">"London" },{ <span class="hljs-string">"Netherland",<span class="hljs-string">"Amsterdam" },{ <span class="hljs-string">"Japan",<span class="hljs-string">"Tokyo" },{ <span class="hljs-string">"France",<span class="hljs-string">"Paris" } };

Map countryCapitals = ArrayUtils.toMap(countries);  

Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a>.<span class="hljs-keyword"&gt;out.println(<span class="hljs-string"&gt;"Capital of Japan is " + countryCapitals.<span class="hljs-keyword"&gt;get(<span class="hljs-string"&gt;"Japan"));  
Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a>.<span class="hljs-keyword"&gt;out.println(<span class="hljs-string"&gt;"Capital of France is " + countryCapitals.<span class="hljs-keyword"&gt;get(<span class="hljs-string"&gt;"France"));  

}
}

18. Send mail

<span class="hljs-keyword">public <span class="hljs-keyword">void <span class="hljs-title">postMail( String recipients,String subject,String message,String from) <span class="hljs-keyword">throws MessagingException
{
<span class="hljs-keyword">boolean debug = <span class="hljs-keyword">false;

 <span class="hljs-comment"&gt;//Set the host smtp address  
 Properties props = <span class="hljs-keyword"&gt;new Properties();  
 props.put(<span class="hljs-string"&gt;"mail.smtp.host",<span class="hljs-string"&gt;"smtp.example.com");  

<span class="hljs-comment"&gt;// create some properties and get the default Session  
Session session = Session.getDefaultInstance(props,<span class="hljs-keyword"&gt;null);  
session.setDebug(debug);  

<span class="hljs-comment"&gt;// create a message  
Message msg = <span class="hljs-keyword"&gt;new MimeMessage(session);  

<span class="hljs-comment"&gt;// set the from and to address  
InternetAddress addressFrom = <span class="hljs-keyword"&gt;new InternetAddress(from);  
msg.setFrom(addressFrom);  

InternetAddress[] addressTo = <span class="hljs-keyword"&gt;new InternetAddress[recipients.length];  
<span class="hljs-keyword"&gt;for (<span class="hljs-keyword"&gt;int i = <span class="hljs-number"&gt;0; i < recipients.length; i++)  
{  
    addressTo[i] = <span class="hljs-keyword"&gt;new InternetAddress(recipients[i]);  
}  
msg.setRecipients(Message.RecipientType.TO,addressTo);  

<span class="hljs-comment"&gt;// Optional : You can also set your custom headers in the Email if you Want  
msg.addHeader(<span class="hljs-string"&gt;"MyHeaderName",<span class="hljs-string"&gt;"myHeaderValue");  

<span class="hljs-comment"&gt;// Setting the Subject and Content Type  
msg.setSubject(subject);  
msg.setContent(message,<span class="hljs-string"&gt;"text/plain");  
Transport.send(msg);  

}

19. Send HTTP request for proxy data

<span class="hljs-keyword">public <span class="hljs-class"><span class="hljs-keyword">class <span class="hljs-title">Main {
<span class="hljs-keyword">public <span class="hljs-keyword">static <span class="hljs-keyword">void <span class="hljs-title">main(String[] args) {
<span class="hljs-keyword">try {
URL my_url = <span class="hljs-keyword">new URL(<span class="hljs-string">"http://coolshell.cn/");
BufferedReader br = <span class="hljs-keyword">new BufferedReader(<span class="hljs-keyword">new InputStreamReader(my_url.openStream()));
String strTemp = <span class="hljs-string">"";
<span class="hljs-keyword">while(<span class="hljs-keyword">null != (strTemp = br.readLine())){
System.out.println(strTemp);
}
} <span class="hljs-keyword">catch (Exception ex) {
ex.printStackTrace();
}
}
}

20. Change the size of the array

 <span class="hljs-comment">// Test routine for resizeArray().
<span class="hljs-keyword">public <span class="hljs-keyword">static <span class="hljs-keyword">void <span class="hljs-title">main (String[] args) {
<span class="hljs-keyword">int[] a = {<span class="hljs-number">1,<span class="hljs-number">2,<span class="hljs-number">3};
a = (<span class="hljs-keyword">int[])resizeArray(a,<span class="hljs-number">5);
a[<span class="hljs-number">3] = <span class="hljs-number">4;
a[<span class="hljs-number">4] = <span class="hljs-number">5;
<span class="hljs-keyword">for (<span class="hljs-keyword">int i=<span class="hljs-number">0; i<a.length; i++)
System.out.println (a[i]);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>