20段代码
1.字符串有整型的相互转换
Stringa = String.valueOf(2); //integer tonumeric string
inti = Integer.parseInt(a); //numeric string to an int
2.向文件末尾添加内容
BufferedWriterout = null;
try{
out = new BufferedWriter(newFileWriter(”filename”, true));
out.write(”aString”);
}catch (IOException e) {
// error processing code
}finally {
if (out != null) {
out.close();
}
}
3.得到当前方法的名字
StringmethodName = Thread.currentThread().getStackTrace()[1].getMethodName();
4.转字符串到日期
java.util.Date= java.text.DateFormat.getDateInstance().parse(date String);
或者是:
SimpleDateFormatformat = new SimpleDateFormat( "dd.MM.yyyy" );
Datedate = format.parse( myString );
5.使用JDBC链接Oracle
publicclass OracleJdbcTest
{
String driverClass ="oracle.jdbc.driver.OracleDriver";
Connection con;
public void init(FileInputStream fs) throwsClassNotFoundException, SQLException, FileNotFoundException, IOException
{
Properties props = newProperties();
props.load(fs);
String url =props.getProperty("db.url");
String userName =props.getProperty("db.user");
String password =props.getProperty("db.password");
Class.forName(driverClass);
con=DriverManager.getConnection(url,userName, password);
}
public void fetch() throws SQLException,IOException
{
PreparedStatement ps =con.prepareStatement("select SYSDATE from dual");
ResultSet rs = ps.executeQuery();
while (rs.next())
{
// do the thing you do
}
rs.close();
ps.close();
}
public static void main(String[] args)
{
OracleJdbcTest test = newOracleJdbcTest();
test.init();
test.fetch();
}
}
6.把Javautil.Date 转成sql.Date
java.util.DateutilDate = new java.util.Date();
java.sql.DatesqlDate = new java.sql.Date(utilDate.getTime());
7.使用NIO进行快速的文件拷贝
publicstatic void fileCopy( File in, File out )
throws IOException
{
FileChannel inChannel = newFileInputStream( in ).getChannel();
FileChannel outChannel = newFileOutputStream( out ).getChannel();
try
{
// inChannel.transferTo(0,inChannel.size(), outChannel); //original -- apparently has trouble copying large files on Windows
// magic number for Windows, 64Mb -32Kb)
int maxCount = (64 * 1024 * 1024) -(32 * 1024);
long size = inChannel.size();
long position = 0;
while ( position < size )
{
position +=inChannel.transferTo( position, maxCount, outChannel );
}
}
finally
{
if ( inChannel != null )
{
inChannel.close();
}
if ( outChannel != null )
{
outChannel.close();
}
}
}
8.创建图片的缩略图
privatevoid createThumbnail(String filename, int thumbWidth, int thumbHeight, intquality, String outFilename)
throws InterruptedException,FileNotFoundException, IOException
{
// load image from filename
Image image =Toolkit.getDefaultToolkit().getImage(filename);
MediaTracker mediaTracker = newMediaTracker(new Container());
mediaTracker.addImage(image, 0);
mediaTracker.waitForID(0);
// use this to test for errors at thispoint: System.out.println(mediaTracker.isErrorAny());
// determine thumbnail size from WIDTHand HEIGHT
double thumbRatio = (double)thumbWidth/ (double)thumbHeight;
int imageWidth =image.getWidth(null);
int imageHeight =image.getHeight(null);
double imageRatio = (double)imageWidth/ (double)imageHeight;
if (thumbRatio < imageRatio) {
thumbHeight = (int)(thumbWidth /imageRatio);
} else {
thumbWidth = (int)(thumbHeight *imageRatio);
}
// draw original image to thumbnailimage object and
// scale it to the new sizeon-the-fly
BufferedImage thumbImage = newBufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D =thumbImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image, 0, 0,thumbWidth, thumbHeight, null);
// save thumbnail image tooutFilename
BufferedOutputStream out = newBufferedOutputStream(new FileOutputStream(outFilename));
JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param =encoder.getDefaultJPEGEncodeParam(thumbImage);
quality = Math.max(0, Math.min(quality,100));
param.setQuality((float)quality /100.0f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(thumbImage);
out.close();
}
9.创建JSON格式的数据
请先阅读这篇文章 了解一些细节,
并下面这个JAR 文件:json-rpc-1.0.jar (75 kb)
importorg.json.JSONObject;
...
...
JSONObjectjson = new JSONObject();
json.put("city","Mumbai");
json.put("country","India");
...
Stringoutput = json.toString();
...
10.使用iTextJAR生成PDF
阅读这篇文章 了解更多细节
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.OutputStream;
importjava.util.Date;
importcom.lowagie.text.Document;
importcom.lowagie.text.Paragraph;
importcom.lowagie.text.pdf.PdfWriter;
publicclass GeneratePDF {
public static void main(String[] args){
try {
OutputStream file = newFileOutputStream(new File("C:\\Test.pdf"));
Document document = newDocument();
PdfWriter.getInstance(document,file);
document.open();
document.add(new Paragraph("HelloKiran"));
document.add(new Paragraph(newDate().toString()));
document.close();
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
11.HTTP 代理设置
阅读这篇 文章 了解更多细节。
System.getProperties().put("http.proxyHost","someProxyURL");
System.getProperties().put("http.proxyPort","someProxyPort");
System.getProperties().put("http.proxyUser","someUserName");
System.getProperties().put("http.proxyPassword","somePassword");
2.单实例Singleton示例
请先阅读这篇文章 了解更多信息
publicclass SimpleSingleton {
private static SimpleSingletonsingleInstance = newSimpleSingleton();
//Marking default constructor private
//to avoid direct instantiation.
private SimpleSingleton() {
}
//Get instance for classSimpleSingleton
public static SimpleSingleton getInstance(){
return singleInstance;
}
}
另一种实现
publicenum SimpleSingleton {
INSTANCE;
public void doSomething() {
}
}
//Callthe method from Singleton:
SimpleSingleton.INSTANCE.doSomething();
13.抓屏程序
阅读这篇文章 获得更多信息。
importjava.awt.Dimension;
importjava.awt.Rectangle;
importjava.awt.Robot;
importjava.awt.Toolkit;
importjava.awt.image.BufferedImage;
importjavax.imageio.ImageIO;
importjava.io.File;
...
publicvoid captureScreen(String fileName) throws Exception {
Dimension screenSize =Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = newRectangle(screenSize);
Robot robot = new Robot();
BufferedImage image =robot.createScreenCapture(screenRectangle);
ImageIO.write(image, "png", newFile(fileName));
}
...
14.列出文件和目录
Filedir = new File("directoryName");
String[] children = dir.list();
if (children == null) {
// Either dir does not exist or is not adirectory
} else {
for (int i=0; i < children.length;i++) {
// Get filename of file ordirectory
String filename = children[i];
}
}
// It is also possible to filter the list ofreturned files.
// This example does not return any filesthat start with `.'.
FilenameFilter filter = new FilenameFilter(){
public boolean accept(File dir, Stringname) {
return!name.startsWith(".");
}
};
children = dir.list(filter);
// The list of files can also be retrieved asFile objects
File[] files = dir.listFiles();
// This filter only returns directories
FileFilter fileFilter = new FileFilter(){
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);
15.创建ZIP和JAR文件
importjava.util.zip.*;
importjava.io.*;
publicclass ZipIt {
public static void main(String args[])throws IOException {
if (args.length < 2) {
System.err.println("usage:java ZipIt Zip.zip file1 file2 file3");
System.exit(-1);
}
File zipFile = new File(args[0]);
if (zipFile.exists()) {
System.err.println("Zip filealready exists, please try another");
System.exit(-2);
}
FileOutputStream fos = newFileOutputStream(zipFile);
ZipOutputStream zos = newZipOutputStream(fos);
int bytesRead;
byte[] buffer = new byte[1024];
CRC32 crc = new CRC32();
for (int i=1, n=args.length; i < n;i++) {
String name = args[i];
File file = new File(name);
if (!file.exists()) {
System.err.println("Skipping: " + name);
continue;
}
BufferedInputStream bis = newBufferedInputStream(
newFileInputStream(file));
crc.reset();
while ((bytesRead =bis.read(buffer)) != -1) {
crc.update(buffer, 0,bytesRead);
}
bis.close();
// Reset to beginning of inputstream
bis = new BufferedInputStream(
newFileInputStream(file));
ZipEntry entry = newZipEntry(name);
entry.setMethod(ZipEntry.STORED);
entry.setCompressedSize(file.length());
entry.setSize(file.length());
entry.setCrc(crc.getValue());
zos.putNextEntry(entry);
while ((bytesRead =bis.read(buffer)) != -1) {
zos.write(buffer, 0,bytesRead);
}
bis.close();
}
zos.close();
}
}
16.解析/读取XML 文件
XML文件
<?xmlversion="1.0"?>
<students>
<student>
<name>John</name>
<grade>B</grade>
<age>12</age>
</student>
<student>
<name>Mary</name>
<grade>A</grade>
<age>11</age>
</student>
<student>
<name>Simon</name>
<grade>A</grade>
<age>18</age>
</student>
</students>
Java代码:
ackagenet.viralpatel.java.xmlparser;
importjava.io.File;
importjavax.xml.parsers.DocumentBuilder;
importjavax.xml.parsers.DocumentBuilderFactory;
importorg.w3c.dom.Document;
importorg.w3c.dom.Element;
importorg.w3c.dom.Node;
importorg.w3c.dom.NodeList;
publicclass XMLParser {
public void getAllUserNames(StringfileName) {
try {
DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
DocumentBuilder db =dbf.newDocumentBuilder();
File file = newFile(fileName);
if (file.exists()) {
Document doc =db.parse(file);
Element docEle =doc.getDocumentElement();
// Print root element of thedocument
System.out.println("Rootelement of the document: "
+docEle.getNodeName());
NodeList studentList =docEle.getElementsByTagName("student");
// Print total student elementsin document
System.out
.println("Totalstudents: " + studentList.getLength());
if (studentList != null&& studentList.getLength() > 0) {
for (int i = 0; i <studentList.getLength(); i++) {
Node node =studentList.item(i);
if (node.getNodeType()== Node.ELEMENT_NODE) {
System.out
.println("=====================");
Element e =(Element) node;
NodeList nodeList =e.getElementsByTagName("name");
System.out.println("Name: "
+nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
nodeList =e.getElementsByTagName("grade");
System.out.println("Grade: "
+nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
nodeList =e.getElementsByTagName("age");
System.out.println("Age: "
+nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
}
}
} else {
System.exit(1);
}
}
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args){
XMLParser parser = newXMLParser();
parser.getAllUserNames("c:\\test.xml");
}
}
17.把Array转换成Map
importjava.util.Map;
importorg.apache.commons.lang.ArrayUtils;
publicclass Main {
public static void main(String[] args) {
String[][] countries = { { "UnitedStates", "New York" }, { "United Kingdom","London" },
{ "Netherland","Amsterdam" }, { "Japan", "Tokyo" }, {"France", "Paris" } };
Map countryCapitals =ArrayUtils.toMap(countries);
System.out.println("Capital of Japanis " + countryCapitals.get("Japan"));
System.out.println("Capital of Franceis " + countryCapitals.get("France"));
}
}
18.发送邮件
importjavax.mail.*;
importjavax.mail.internet.*;
importjava.util.*;
publicvoid postMail( String recipients[ ], String subject, String message , Stringfrom) throws MessagingException
{
boolean debug = false;
//Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host","smtp.example.com");
// create some properties and get thedefault Session
Session session =Session.getDefaultInstance(props, null);
session.setDebug(debug);
// create a message
Message msg = newMimeMessage(session);
// set the from and to address
InternetAddress addressFrom = newInternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = newInternetAddress[recipients.length];
for (int i = 0; i < recipients.length;i++)
{
addressTo[i] = newInternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO,addressTo);
// Optional : You can also set your customheaders in the Email if you Want
msg.addHeader("MyHeaderName","myHeaderValue");
// Setting the Subject and ContentType
msg.setSubject(subject);
msg.setContent(message,"text/plain");
Transport.send(msg);
}
19.发送代数据的HTTP请求
importjava.io.BufferedReader;
importjava.io.InputStreamReader;
importjava.net.URL;
publicclass Main {
public static void main(String[] args) {
try {
URL my_url = newURL("http://coolshell.cn/");
BufferedReader br = new BufferedReader(newInputStreamReader(my_url.openStream()));
String strTemp = "";
while(null != (strTemp =br.readLine())){
System.out.println(strTemp);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
20.改变数组的大小
/**
*Reallocates an array with a new size, and copies the contents
*of the old array to the new array.
*@param oldArray the old array, to bereallocated.
*@param newSize the new array size.
*@return A new array with thesame contents.
*/
privatestatic Object resizeArray (Object oldArray, int newSize) {
int oldSize =java.lang.reflect.Array.getLength(oldArray);
Class elementType =oldArray.getClass().getComponentType();
Object newArray =java.lang.reflect.Array.newInstance(
elementType,newSize);
int preserveLength =Math.min(oldSize,newSize);
if (preserveLength > 0)
System.arraycopy(oldArray,0,newArray,0,preserveLength);
return newArray;
}
//Test routine for resizeArray().
publicstatic void main (String[] args) {
int[] a = {1,2,3};
a = (int[])resizeArray(a,5);
a[3] = 4;
a[4] = 5;
for (int i=0; i<a.length; i++)
System.out.println (a[i]);
}