下面是20个非常有用的Java程序片段,希望能对你有用。
1. 字符串有整型的相互转换
2 |
String a = String.valueOf( 2 ); |
3 |
int i = Integer.parseInt(a); |
2. 向文件末尾添加内容
02 |
BufferedWriter out = null ; |
04 |
out = new BufferedWriter( new FileWriter(”filename”, true )); |
06 |
} catch (IOException e) { |
3. 得到当前方法的名字
1 |
String methodName = Thread.currentThread().getStackTrace()[ 1 ].getMethodName(); |
4. 转字符串到日期
2 |
java.util.Date = java.text.DateFormat.getDateInstance().parse(date String); |
或者是:
2 |
SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" ); |
3 |
Date date = format.parse( myString ); |
5. 使用JDBC链接Oracle
01 |
public class OracleJdbcTest |
03 |
String driverClass = "oracle.jdbc.driver.OracleDriver" ; |
07 |
public void init(FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException |
09 |
Properties props = new Properties(); |
11 |
String url = props.getProperty( "db.url" ); |
12 |
String userName = props.getProperty( "db.user" ); |
13 |
String password = props.getProperty( "db.password" ); |
14 |
Class.forName(driverClass); |
16 |
con=DriverManager.getConnection(url, userName, password); |
19 |
public void fetch() throws SQLException, IOException |
21 |
PreparedStatement ps = con.prepareStatement( "select SYSDATE from dual" ); |
22 |
ResultSet rs = ps.executeQuery(); |
32 |
public static void main(String[] args) |
34 |
OracleJdbcTest test = new OracleJdbcTest(); |
6. 把 Java util.Date 转成 sql.Date
1 |
java.util.Date utilDate = new java.util.Date(); |
2 |
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime()); |
7. 使用NIO进行快速的文件拷贝
01 |
public static void fileCopy( File in, File out ) |
04 |
FileChannel inChannel = new FileInputStream( in ).getChannel(); |
05 |
FileChannel outChannel = new FileOutputStream( out ).getChannel(); |
11 |
int maxCount = ( 64 * 1024 * 1024 ) - ( 32 * 1024 ); |
12 |
long size = inChannel.size(); |
14 |
while ( position < size ) |
16 |
position += inChannel.transferTo( position, maxCount, outChannel ); |
21 |
if ( inChannel != null ) |
25 |
if ( outChannel != null ) |
8. 创建图片的缩略图
01 |
private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename) |
02 |
throws InterruptedException, FileNotFoundException, IOException |
05 |
Image image = Toolkit.getDefaultToolkit().getImage(filename); |
06 |
MediaTracker mediaTracker = new MediaTracker( new Container()); |
07 |
mediaTracker.addImage(image, 0 ); |
08 |
mediaTracker.waitForID( 0 ); |
12 |
double thumbRatio = ( double )thumbWidth / ( double )thumbHeight; |
13 |
int imageWidth = image.getWidth( null ); |
14 |
int imageHeight = image.getHeight( null ); |
15 |
double imageRatio = ( double )imageWidth / ( double )imageHeight; |
16 |
if (thumbRatio < imageRatio) { |
17 |
thumbHeight = ( int )(thumbWidth / imageRatio); |
19 |
thumbWidth = ( int )(thumbHeight * imageRatio); |
24 |
BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); |
25 |
Graphics2D graphics2D = thumbImage.createGraphics(); |
26 |
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); |
27 |
graphics2D.drawImage(image, 0 , 0 , thumbWidth, thumbHeight, null ); |
30 |
BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream(outFilename)); |
31 |
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); |
32 |
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage); |
33 |
quality = Math.max( 0 , Math.min(quality, 100 )); |
34 |
param.setQuality(( float )quality / 100 .0f, false ); |
35 |
encoder.setJPEGEncodeParam(param); |
36 |
encoder.encode(thumbImage); |
9. 创建 JSON 格式的数据
请先阅读这篇文章 了解一些细节,
并下面这个JAR 文件:json-rpc-1.0.jar (75 kb)
1 |
import org.json.JSONObject; |
4 |
JSONObject json = new JSONObject(); |
5 |
json.put( "city" , "Mumbai" ); |
6 |
json.put( "country" , "India" ); |
8 |
String output = json.toString(); |
10. 使用iText JAR生成PDF
阅读这篇文章 了解更多细节
03 |
import java.io.FileOutputStream; |
04 |
import java.io.OutputStream; |
05 |
import java.util.Date; |
07 |
import com.lowagie.text.Document; |
08 |
import com.lowagie.text.Paragraph; |
09 |
import com.lowagie.text.pdf.PdfWriter; |
11 |
public class GeneratePDF { |
13 |
public static void main(String[] args) { |
15 |
OutputStream file = new FileOutputStream( new File( "C:\\Test.pdf" )); |
17 |
Document document = new Document(); |
18 |
PdfWriter.getInstance(document, file); |
20 |
document.add( new Paragraph( "Hello Kiran" )); |
21 |
document.add( new Paragraph( new Date().toString())); |
26 |
} catch (Exception e) { |
11. HTTP 代理设置
阅读这篇 文章 了解更多细节。
2 |
System.getProperties().put( "http.proxyHost" , "someProxyURL" ); |
3 |
System.getProperties().put( "http.proxyPort" , "someProxyPort" ); |
4 |
System.getProperties().put( "http.proxyUser" , "someUserName" ); |
5 |
System.getProperties().put( "http.proxyPassword" , "somePassword" ); |
12. 单实例Singleton 示例
请先阅读这篇文章 了解更多信息
02 |
public class SimpleSingleton { |
03 |
private static SimpleSingleton singleInstance = new SimpleSingleton(); |
07 |
private SimpleSingleton() { |
11 |
public static SimpleSingleton getInstance() { |
13 |
return singleInstance; |
另一种实现
1 |
public enum SimpleSingleton { |
3 |
public void doSomething() { |
8 |
SimpleSingleton.INSTANCE.doSomething(); |
13. 抓屏程序
阅读这篇文章 获得更多信息。
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; |
11 |
public void captureScreen(String fileName) throws Exception { |
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)); |
14. 列出文件和目录
01 |
File dir = new File( "directoryName" ); |
02 |
String[] children = dir.list(); |
03 |
if (children == null ) { |
06 |
for ( int i= 0 ; i < children.length; i++) { |
08 |
String filename = children[i]; |
14 |
FilenameFilter filter = new FilenameFilter() { |
15 |
public boolean accept(File dir, String name) { |
16 |
return !name.startsWith( "." ); |
19 |
children = dir.list(filter); |
22 |
File[] files = dir.listFiles(); |
25 |
FileFilter fileFilter = new FileFilter() { |
26 |
public boolean accept(File file) { |
27 |
return file.isDirectory(); |
30 |
files = dir.listFiles(fileFilter); |
15. 创建ZIP和JAR文件
02 |
import java.util.zip.*; |
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" ); |
11 |
File zipFile = new File(args[ 0 ]); |
12 |
if (zipFile.exists()) { |
13 |
System.err.println( "Zip file already exists, please try another" ); |
16 |
FileOutputStream fos = new FileOutputStream(zipFile); |
17 |
ZipOutputStream zos = new ZipOutputStream(fos); |
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); |
25 |
System.err.println( "Skipping: " + name); |
28 |
BufferedInputStream bis = new BufferedInputStream( |
29 |
new FileInputStream(file)); |
31 |
while ((bytesRead = bis.read(buffer)) != - 1 ) { |
32 |
crc.update(buffer, 0 , bytesRead); |
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); |
16. 解析/读取XML 文件
XML文件
Java代码
02 |
package net.viralpatel.java.xmlparser; |
05 |
import javax.xml.parsers.DocumentBuilder; |
06 |
import javax.xml.parsers.DocumentBuilderFactory; |
08 |
import org.w3c.dom.Document; |
09 |
import org.w3c.dom.Element; |
10 |
import org.w3c.dom.Node; |
11 |
import org.w3c.dom.NodeList; |
13 |
public class XMLParser { |
15 |
public void getAllUserNames(String fileName) { |
17 |
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); |
18 |
DocumentBuilder db = dbf.newDocumentBuilder(); |
19 |
File file = new File(fileName); |
21 |
Document doc = db.parse(file); |
22 |
Element docEle = doc.getDocumentElement(); |
25 |
System.out.println( "Root element of the document: " |
26 |
+ docEle.getNodeName()); |
28 |
NodeList studentList = docEle.getElementsByTagName( "student" ); |
32 |
.println( "Total students: " + studentList.getLength()); |
34 |
if (studentList != null && studentList.getLength() > 0 ) { |
35 |
for ( int i = 0 ; i < studentList.getLength(); i++) { |
37 |
Node node = studentList.item(i); |
39 |
if (node.getNodeType() == Node.ELEMENT_NODE) { |
42 |
.println( "=====================" ); |
44 |
Element e = (Element) node; |
45 |
NodeList nodeList = e.getElementsByTagName( "name" ); |
46 |
System.out.println( "Name: " |
47 |
+ nodeList.item( 0 ).getChildNodes().item( 0 ) |
50 |
nodeList = e.getElementsByTagName( "grade" ); |
51 |
System.out.println( "Grade: " |
52 |
+ nodeList.item( 0 ).getChildNodes().item( 0 ) |
55 |
nodeList = e.getElementsByTagName( "age" ); |
56 |
System.out.println( "Age: " |
57 |
+ nodeList.item( 0 ).getChildNodes().item( 0 ) |
65 |
} catch (Exception e) { |
66 |
System.out.println(e); |
69 |
public static void main(String[] args) { |
71 |
XMLParser parser = new XMLParser(); |
72 |
parser.getAllUserNames( "c:\\test.xml" ); |
17. 把 Array 转换成 Map
03 |
import org.apache.commons.lang.ArrayUtils; |
07 |
public static void main(String[] args) { |
08 |
String[][] countries = { { "United States" , "New York" }, { "United Kingdom" , "London" }, |
09 |
{ "Netherland" , "Amsterdam" }, { "Japan" , "Tokyo" }, { "France" , "Paris" } }; |
11 |
Map countryCapitals = ArrayUtils.toMap(countries); |
13 |
System.out.println( "Capital of Japan is " + countryCapitals.get( "Japan" )); |
14 |
System.out.println( "Capital of France is " + countryCapitals.get( "France" )); |
18. 发送邮件
02 |
import javax.mail.internet.*; |
05 |
public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException |
07 |
boolean debug = false ; |
10 |
Properties props = new Properties(); |
11 |
props.put( "mail.smtp.host" , "smtp.example.com" ); |
14 |
Session session = Session.getDefaultInstance(props, null ); |
15 |
session.setDebug(debug); |
18 |
Message msg = new MimeMessage(session); |
21 |
InternetAddress addressFrom = new InternetAddress(from); |
22 |
msg.setFrom(addressFrom); |
24 |
InternetAddress[] addressTo = new InternetAddress[recipients.length]; |
25 |
for ( int i = 0 ; i < recipients.length; i++) |
27 |
addressTo[i] = new InternetAddress(recipients[i]); |
29 |
msg.setRecipients(Message.RecipientType.TO, addressTo); |
32 |
msg.addHeader( "MyHeaderName" , "myHeaderValue" ); |
35 |
msg.setSubject(subject); |
36 |
msg.setContent(message, "text/plain" ); |
19. 发送代数据的HTTP 请求
02 |
import java.io.BufferedReader; |
03 |
import java.io.InputStreamReader; |
07 |
public static void main(String[] args) { |
09 |
URL my_url = new URL( "" ); |
10 |
BufferedReader br = new BufferedReader( new InputStreamReader(my_url.openStream())); |
12 |
while ( null != (strTemp = br.readLine())){ |
13 |
System.out.println(strTemp); |
15 |
} catch (Exception ex) { |
20. 改变数组的大小
03 |
* Reallocates an array with a new size, and copies the contents |
04 |
* of the old array to the new array. |
05 |
* @param oldArray the old array, to be reallocated. |
06 |
* @param newSize the new array size. |
07 |
* @return A new array with the same contents. |
09 |
private static Object resizeArray (Object oldArray, int newSize) { |
10 |
int oldSize = java.lang.reflect.Array.getLength(oldArray); |
11 |
Class elementType = oldArray.getClass().getComponentType(); |
12 |
Object newArray = java.lang.reflect.Array.newInstance( |
14 |
int preserveLength = Math.min(oldSize,newSize); |
15 |
if (preserveLength > 0 ) |
16 |
System.arraycopy (oldArray, 0 ,newArray, 0 ,preserveLength); |
21 |
public static void main (String[] args) { |
23 |
a = ( int [])resizeArray(a, 5 ); |
27 |
System.out.println (a[i]); |
阅读(723) | 评论(0) | 转发(0) |