`
顽石OK07
  • 浏览: 81291 次
  • 性别: Icon_minigender_2
  • 来自: 上海
社区版块
存档分类
最新评论

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

阅读更多

原文网址是:http://haofeng0305.iteye.com/blog/752236

 

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

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

Java代码 复制代码
  1.      
  2. String a = String.valueOf(2);   //integer to numeric string     
  3. int i = Integer.parseInt(a); //numeric string to an int   


2. 向文件末尾添加内容

  
BufferedWriter out = null;  
try {  
    out = new BufferedWriter(new FileWriter(”filename”, true));  
    out.write(”aString”);  
} catch (IOException e) {  
    // error processing code  
} finally {  
    if (out != null) {  
        out.close();  
    }  
} 


3. 得到当前方法的名字

Java代码 复制代码
  1. String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();   

4. 转字符串到日期
Java代码 复制代码
  1.      
  2. java.util.Date = java.text.DateFormat.getDateInstance().parse(date String);    
  3. 或者是:   
  4.   
  5.      
  6. SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );     
  7. Date date = format.parse( myString );   

5. 使用JDBC链接Oracle
Java代码 复制代码
  1. public class OracleJdbcTest     
  2. {     
  3.     String driverClass = "oracle.jdbc.driver.OracleDriver";     
  4.      
  5.     Connection con;     
  6.      
  7.     public void init(FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException     
  8.     {     
  9.         Properties props = new Properties();     
  10.         props.load(fs);     
  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);     
  15.      
  16.         con=DriverManager.getConnection(url, userName, password);     
  17.     }     
  18.      
  19.     public void fetch() throws SQLException, IOException     
  20.     {     
  21.         PreparedStatement ps = con.prepareStatement("select SYSDATE from dual");     
  22.         ResultSet rs = ps.executeQuery();     
  23.      
  24.         while (rs.next())     
  25.         {     
  26.             // do the thing you do     
  27.         }     
  28.         rs.close();     
  29.         ps.close();     
  30.     }     
  31.      
  32.     public static void main(String[] args)     
  33.     {     
  34.         OracleJdbcTest test = new OracleJdbcTest();     
  35.         test.init();     
  36.         test.fetch();     
  37.     }     
  38. }   

6. 把 Java util.Date 转成 sql.Date
Java代码 复制代码
  1. java.util.Date utilDate = new java.util.Date();     
  2. java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());   


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

Java代码 复制代码
  1.     
  2.   
  3. public static void fileCopy( File in, File out )     
  4.             throws IOException     
  5.     {     
  6.         FileChannel inChannel = new FileInputStream( in ).getChannel();     
  7.         FileChannel outChannel = new FileOutputStream( out ).getChannel();     
  8.         try    
  9.         {     
  10. //          inChannel.transferTo(0, inChannel.size(), outChannel);      // original -- apparently has trouble copying large files on Windows     
  11.      
  12.             // magic number for Windows, 64Mb - 32Kb)     
  13.             int maxCount = (64 * 1024 * 1024) - (32 * 1024);     
  14.             long size = inChannel.size();     
  15.             long position = 0;     
  16.             while ( position < size )     
  17.             {     
  18.                position += inChannel.transferTo( position, maxCount, outChannel );     
  19.             }     
  20.         }     
  21.         finally    
  22.         {     
  23.             if ( inChannel != null )     
  24.             {     
  25.                inChannel.close();     
  26.             }     
  27.             if ( outChannel != null )     
  28.             {     
  29.                 outChannel.close();     
  30.             }     
  31.         }     
  32.     }   

8. 创建图片的缩略图
Java代码 复制代码
  1. private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename)     
  2.         throws InterruptedException, FileNotFoundException, IOException     
  3.     {     
  4.         // load image from filename     
  5.         Image image = Toolkit.getDefaultToolkit().getImage(filename);     
  6.         MediaTracker mediaTracker = new MediaTracker(new Container());     
  7.         mediaTracker.addImage(image, 0);     
  8.         mediaTracker.waitForID(0);     
  9.         // use this to test for errors at this point: System.out.println(mediaTracker.isErrorAny());     
  10.      
  11.         // determine thumbnail size from WIDTH and HEIGHT     
  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);     
  18.         } else {     
  19.             thumbWidth = (int)(thumbHeight * imageRatio);     
  20.         }     
  21.      
  22.         // draw original image to thumbnail image object and     
  23.         // scale it to the new size on-the-fly     
  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, 00, thumbWidth, thumbHeight, null);     
  28.      
  29.         // save thumbnail image to outFilename     
  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);     
  37.         out.close();     
  38.     }   

9. 创建 JSON 格式的数据
Java代码 复制代码
  1. 请先阅读这篇文章 了解一些细节,   
  2. 并下面这个JAR 文件:json-rpc-1.0.jar (75 kb)   
  3.   
  4. import org.json.JSONObject;     
  5. ...     
  6. ...     
  7. JSONObject json = new JSONObject();     
  8. json.put("city""Mumbai");     
  9. json.put("country""India");     
  10. ...     
  11. String output = json.toString();     
  12. ...   
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics