原文地址:http://geek.csdn.net/news/detail/236591
下面是20个非常有用的Java程序片段,希望能对你有用。
1. 字符串有整型的相互转换
2. 向文件末尾添加内容
3. 得到当前方法的名字
4. 转字符串到日期
或者是:
5. 使用JDBC链接Oracle
Connection con;
<span class="hljs-keyword">public <span class="hljs-keyword">void <span class="hljs-title">init(FileInputStream fs) <span class="hljs-keyword">throws ClassNotFoundException,SQLException,FileNotFoundException,IOException
{
Properties props = <span class="hljs-keyword">new Properties();
props.load(fs);
String url = props.getProperty(<span class="hljs-string">"db.url");
String userName = props.getProperty(<span class="hljs-string">"db.user");
String password = props.getProperty(<span class="hljs-string">"db.password");
Class.forName(driverClass);
con=DriverManager.getConnection(url,userName,password);
}
<span class="hljs-keyword">public <span class="hljs-keyword">void <span class="hljs-title">fetch() <span class="hljs-keyword">throws SQLException,IOException
{
PreparedStatement ps = con.prepareStatement(<span class="hljs-string">"select SYSDATE from dual");
ResultSet rs = ps.executeQuery();
<span class="hljs-keyword">while (rs.next())
{
<span class="hljs-comment">// do the thing you do
}
rs.close();
ps.close();
}
<span class="hljs-keyword">public <span class="hljs-keyword">static <span class="hljs-keyword">void <span class="hljs-title">main(String[] args)
{
OracleJdbcTest test = <span class="hljs-keyword">new OracleJdbcTest();
test.init();
test.fetch();
}
}
6. 把 Java util.Date 转成 sql.Date
7. 使用NIO进行快速的文件拷贝
<span class="hljs-comment">// magic number for Windows,64Mb - 32Kb)
<span class="hljs-keyword">int maxCount = (<span class="hljs-number">64 * <span class="hljs-number">1024 * <span class="hljs-number">1024) - (<span class="hljs-number">32 * <span class="hljs-number">1024);
<span class="hljs-keyword">long size = inChannel.size();
<span class="hljs-keyword">long position = <span class="hljs-number">0;
<span class="hljs-keyword">while ( position < size )
{
position += inChannel.transferTo( position,maxCount,outChannel );
}
}
<span class="hljs-keyword">finally
{
<span class="hljs-keyword">if ( inChannel != <span class="hljs-keyword">null )
{
inChannel.close();
}
<span class="hljs-keyword">if ( outChannel != <span class="hljs-keyword">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">// determine thumbnail size from WIDTH and HEIGHT
<span class="hljs-keyword">double thumbRatio = (<span class="hljs-keyword">double)thumbWidth / (<span class="hljs-keyword">double)thumbHeight;
<span class="hljs-keyword">int imageWidth = image.getWidth(<span class="hljs-keyword">null);
<span class="hljs-keyword">int imageHeight = image.getHeight(<span class="hljs-keyword">null);
<span class="hljs-keyword">double imageRatio = (<span class="hljs-keyword">double)imageWidth / (<span class="hljs-keyword">double)imageHeight;
<span class="hljs-keyword">if (thumbRatio < imageRatio) {
thumbHeight = (<span class="hljs-keyword">int)(thumbWidth / imageRatio);
} <span class="hljs-keyword">else {
thumbWidth = (<span class="hljs-keyword">int)(thumbHeight * imageRatio);
}
<span class="hljs-comment">// draw original image to thumbnail image object and
<span class="hljs-comment">// scale it to the new size on-the-fly
BufferedImage thumbImage = <span class="hljs-keyword">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">0,thumbWidth,<span class="hljs-keyword">null);
<span class="hljs-comment">// save thumbnail image to outFilename
BufferedOutputStream <span class="hljs-keyword">out = <span class="hljs-keyword">new BufferedOutputStream(<span class="hljs-keyword">new FileOutputStream(outFilename));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(<span class="hljs-keyword">out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
quality = Math.max(<span class="hljs-number">0,Math.min(quality,<span class="hljs-number">100));
param.setQuality((<span class="hljs-keyword">float)quality / <span class="hljs-number">100.0f,<span class="hljs-keyword">false);
encoder.setJPEGEncodeParam(param);
encoder.encode(thumbImage);
<span class="hljs-keyword">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">public <span class="hljs-keyword">static <span class="hljs-keyword">void <span class="hljs-title">main(String[] args) {
<span class="hljs-keyword">try {
OutputStream file = <span class="hljs-keyword">new FileOutputStream(<span class="hljs-keyword">new File(<span class="hljs-string">"C:Test.pdf"));
Document document = <span class="hljs-keyword">new Document();
PdfWriter.getInstance(document,file);
document.open();
document.add(<span class="hljs-keyword">new Paragraph(<span class="hljs-string">"Hello Kiran"));
document.add(<span class="hljs-keyword">new Paragraph(<span class="hljs-keyword">new Date().toString()));
document.close();
file.close();
} <span class="hljs-keyword">catch (Exception e) {
e.printStackTrace();
}
}
}
11. HTTP 代理设置
阅读这篇??了解更多细节。
12. 单实例Singleton 示例
请先阅读这篇?了解更多信息
<span class="hljs-comment">//Marking default constructor private
<span class="hljs-comment">//to avoid direct instantiation.
<span class="hljs-keyword">private <span class="hljs-title">SimpleSingleton() {
}
<span class="hljs-comment">//Get instance for class SimpleSingleton
<span class="hljs-keyword">public <span class="hljs-keyword">static SimpleSingleton <span class="hljs-title">getInstance() {
<span class="hljs-keyword">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">.newInstance()<span class="hljs-comment">;
DocumentBuilder db = dbf<span class="hljs-preprocessor">.newDocumentBuilder()<span class="hljs-comment">;
File file = new File(fileName)<span class="hljs-comment">;
if (file<span class="hljs-preprocessor">.exists()) {
Document doc = db<span class="hljs-preprocessor">.parse(file)<span class="hljs-comment">;
Element docEle = doc<span class="hljs-preprocessor">.getDocumentElement()<span class="hljs-comment">;
// Print root element of the document
System<span class="hljs-preprocessor">.out<span class="hljs-preprocessor">.println(<span class="hljs-string">"Root element of the document: "
+ docEle<span class="hljs-preprocessor">.getNodeName())<span class="hljs-comment">;
NodeList studentList = docEle<span class="hljs-preprocessor">.getElementsByTagName(<span class="hljs-string">"student")<span class="hljs-comment">;
// Print total student elements <span class="hljs-keyword">in document
System<span class="hljs-preprocessor">.out
<span class="hljs-preprocessor">.println(<span class="hljs-string">"Total students: " + studentList<span class="hljs-preprocessor">.getLength())<span class="hljs-comment">;
if (studentList != null && studentList<span class="hljs-preprocessor">.getLength() > <span class="hljs-number">0) {
for (int i = <span class="hljs-number">0<span class="hljs-comment">; i < studentList.getLength(); i++) {
Node node = studentList<span class="hljs-preprocessor">.item(i)<span class="hljs-comment">;
if (node<span class="hljs-preprocessor">.getNodeType() == Node<span class="hljs-preprocessor">.ELEMENT_NODE) {
System<span class="hljs-preprocessor">.out
<span class="hljs-preprocessor">.println(<span class="hljs-string">"=====================")<span class="hljs-comment">;
Element e = (Element) node<span class="hljs-comment">;
NodeList nodeList = e<span class="hljs-preprocessor">.getElementsByTagName(<span class="hljs-string">"name")<span class="hljs-comment">;
System<span class="hljs-preprocessor">.out<span class="hljs-preprocessor">.println(<span class="hljs-string">"Name: "
+ nodeList<span class="hljs-preprocessor">.item(<span class="hljs-number">0)<span class="hljs-preprocessor">.getChildNodes()<span class="hljs-preprocessor">.item(<span class="hljs-number">0)
<span class="hljs-preprocessor">.getNodeValue())<span class="hljs-comment">;
nodeList = e<span class="hljs-preprocessor">.getElementsByTagName(<span class="hljs-string">"grade")<span class="hljs-comment">;
System<span class="hljs-preprocessor">.out<span class="hljs-preprocessor">.println(<span class="hljs-string">"Grade: "
+ nodeList<span class="hljs-preprocessor">.item(<span class="hljs-number">0)<span class="hljs-preprocessor">.getChildNodes()<span class="hljs-preprocessor">.item(<span class="hljs-number">0)
<span class="hljs-preprocessor">.getNodeValue())<span class="hljs-comment">;
nodeList = e<span class="hljs-preprocessor">.getElementsByTagName(<span class="hljs-string">"age")<span class="hljs-comment">;
System<span class="hljs-preprocessor">.out<span class="hljs-preprocessor">.println(<span class="hljs-string">"Age: "
+ nodeList<span class="hljs-preprocessor">.item(<span class="hljs-number">0)<span class="hljs-preprocessor">.getChildNodes()<span class="hljs-preprocessor">.item(<span class="hljs-number">0)
<span class="hljs-preprocessor">.getNodeValue())<span class="hljs-comment">;
}
}
} else {
System<span class="hljs-preprocessor">.exit(<span class="hljs-number">1)<span class="hljs-comment">;
}
}
} catch (Exception e) {
System<span class="hljs-preprocessor">.out<span class="hljs-preprocessor">.println(e)<span class="hljs-comment">;
}
}
public static void main(String[] args) {
XMLParser parser = new XMLParser()<span class="hljs-comment">;
parser<span class="hljs-preprocessor">.getAllUserNames(<span class="hljs-string">"c:test.xml")<span class="hljs-comment">;
}
}
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">out.println(<span class="hljs-string">"Capital of Japan is " + countryCapitals.<span class="hljs-keyword">get(<span class="hljs-string">"Japan"));
System.<span class="hljs-keyword">out.println(<span class="hljs-string">"Capital of France is " + countryCapitals.<span class="hljs-keyword">get(<span class="hljs-string">"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">//Set the host smtp address
Properties props = <span class="hljs-keyword">new Properties();
props.put(<span class="hljs-string">"mail.smtp.host",<span class="hljs-string">"smtp.example.com");
<span class="hljs-comment">// create some properties and get the default Session
Session session = Session.getDefaultInstance(props,<span class="hljs-keyword">null);
session.setDebug(debug);
<span class="hljs-comment">// create a message
Message msg = <span class="hljs-keyword">new MimeMessage(session);
<span class="hljs-comment">// set the from and to address
InternetAddress addressFrom = <span class="hljs-keyword">new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = <span class="hljs-keyword">new InternetAddress[recipients.length];
<span class="hljs-keyword">for (<span class="hljs-keyword">int i = <span class="hljs-number">0; i < recipients.length; i++)
{
addressTo[i] = <span class="hljs-keyword">new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO,addressTo);
<span class="hljs-comment">// Optional : You can also set your custom headers in the Email if you Want
msg.addHeader(<span class="hljs-string">"MyHeaderName",<span class="hljs-string">"myHeaderValue");
<span class="hljs-comment">// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message,<span class="hljs-string">"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]);
} (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!