加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

20个非常有用的Java程序片段--转

发布时间:2020-12-14 06:22:55 所属栏目:Java 来源:网络整理
导读:原文地址:http://geek.csdn.net/news/detail/236591 下面是20个非常有用的Java程序片段,希望能对你有用。 1. 字符串有整型的相互转换 2. 向文件末尾添加内容 3. 得到当前方法的名字 4. 转字符串到日期 或者是: 5. 使用JDBC链接Oracle Connection con; spa

原文地址:http://geek.csdn.net/news/detail/236591

下面是20个非常有用的Java程序片段,希望能对你有用。

1. 字符串有整型的相互转换


2. 向文件末尾添加内容


3. 得到当前方法的名字


4. 转字符串到日期


或者是:


5. 使用JDBC链接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,SQLException,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 SQLException,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 OracleJdbcTest();  
    test.init();  
    test.fetch();  
}  

}

6. 把 Java util.Date 转成 sql.Date


7. 使用NIO进行快速的文件拷贝

        <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. 创建图片的缩略图

    <span class="hljs-comment"&gt;// determine 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  
    BufferedOutputStream <span class="hljs-keyword"&gt;out = <span class="hljs-keyword"&gt;new BufferedOutputStream(<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.?创建 JSON 格式的数据

请先阅读?了解一些细节,?并下面这个JAR 文件:


10. 使用iText JAR生成PDF

阅读这篇?了解更多细节

<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 代理设置

阅读这篇??了解更多细节。


12. 单实例Singleton 示例

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

<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;  
}  

}

另一种实现

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

13. 抓屏程序

阅读这篇?获得更多信息。

<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. 列出文件和目录

<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. 创建ZIP和JAR文件


16. 解析/读取XML 文件

XML文件

 
 
     
        John 
        B 
        12 
     
     
        Mary 
        A 
        11 
     
     
        Simon 
        A 
        18 
     

Java代码

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  
            System<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  
            System<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) {  

                        System<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;;  
                        System<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;;  
                        System<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;;  
                        System<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 {  
                System<span class="hljs-preprocessor"&gt;.exit(<span class="hljs-number"&gt;1)<span class="hljs-comment"&gt;;  
            }  
        }  
    } catch (Exception e) {  
        System<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. 把 Array 转换成 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);  

System.<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"));  
System.<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. 发送邮件

<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. 发送代数据的HTTP 请求

<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. 改变数组的大小

 <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]);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读