20非常有用的Java程序片段(1)

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

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

  
  
  
  
  1. String a = String.valueOf(2);   //integer to numeric string  

  2. int i = Integer.parseInt(a); //numeric string to an int

2. 向文件末尾添加内容

  
  
  
  
  1. BufferedWriter out = null;  

  2. try {  

  3.    out = new BufferedWriter(new FileWriter(”filename”, true));  

  4.    out.write(”aString”);  

  5. } catch (IOException e) {  

  6. // error processing code  

  7. } finally {  

  8. if (out != null) {  

  9.        out.close();  

  10.    }  

  11. }  

3. 得到当前方法的名字

  
  
  
  
  1. String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();  

4. 转字符串到日期

  
  
  
  
  1. java.util.Date = java.text.DateFormat.getDateInstance().parse(date String);  

或者是:

  
  
  
  
  1. SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );  

  2. Date date = format.parse( myString );  

5. 使用JDBC链接Oracle

  
  
  
  
  1. publicclass OracleJdbcTest  

  2. {  

  3.    String driverClass = "oracle.jdbc.driver.OracleDriver";  

  4.    Connection con;  

  5. publicvoid init(FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException  

  6.    {  

  7.        Properties props = new Properties();  

  8.        props.load(fs);  

  9.        String url = props.getProperty("db.url");  

  10.        String userName = props.getProperty("db.user");  

  11.        String password = props.getProperty("db.password");  

  12.        Class.forName(driverClass);  

  13.        con=DriverManager.getConnection(url, userName, password);  

  14.    }  

  15. publicvoid fetch() throws SQLException, IOException  

  16.    {  

  17.        PreparedStatement ps = con.prepareStatement("select SYSDATE from dual");  

  18.        ResultSet rs = ps.executeQuery();  

  19. while (rs.next())  

  20.        {  

  21. // do the thing you do  

  22.        }  

  23.        rs.close();  

  24.        ps.close();  

  25.    }  

  26. publicstaticvoid main(String[] args)  

  27.    {  

  28.        OracleJdbcTest test = new OracleJdbcTest();  

  29.        test.init();  

  30.        test.fetch();  

  31.    }  

  32. }  

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进行快速的文件拷贝

  
  
  
  
  1. publicstaticvoid fileCopy( File in, File out )  

  2. throws IOException  

  3.    {  

  4.        FileChannel inChannel = new FileInputStream( in ).getChannel();  

  5.        FileChannel outChannel = new FileOutputStream( out ).getChannel();  

  6. try

  7.        {  

  8. //          inChannel.transferTo(0, inChannel.size(), outChannel);      // original -- apparently has trouble copying large files on Windows  

  9. // magic number for Windows, 64Mb - 32Kb)  

  10. int maxCount = (64 * 1024 * 1024) - (32 * 1024);  

  11. long size = inChannel.size();  

  12. long position = 0;  

  13. while ( position < size )  

  14.            {  

  15.               position += inChannel.transferTo( position, maxCount, outChannel );  

  16.            }  

  17.        }  

  18. finally

  19.        {  

  20. if ( inChannel != null )  

  21.            {  

  22.               inChannel.close();  

  23.            }  

  24. if ( outChannel != null )  

  25.            {  

  26.                outChannel.close();  

  27.            }  

  28.        }  

  29.    }  

8. 创建图片的缩略图

  
  
  
  
  1. privatevoid 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. // determine thumbnail size from WIDTH and HEIGHT  

  11. double thumbRatio = (double)thumbWidth / (double)thumbHeight;  

  12. int imageWidth = image.getWidth(null);  

  13. int imageHeight = image.getHeight(null);  

  14. double imageRatio = (double)imageWidth / (double)imageHeight;  

  15. if (thumbRatio < imageRatio) {  

  16.            thumbHeight = (int)(thumbWidth / imageRatio);  

  17.        } else {  

  18.            thumbWidth = (int)(thumbHeight * imageRatio);  

  19.        }  

  20. // draw original image to thumbnail image object and  

  21. // scale it to the new size on-the-fly  

  22.        BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);  

  23.        Graphics2D graphics2D = thumbImage.createGraphics();  

  24.        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);  

  25.        graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);  

  26. // save thumbnail image to outFilename  

  27.        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename));  

  28.        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  

  29.        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);  

  30.        quality = Math.max(0, Math.min(quality, 100));  

  31.        param.setQuality((float)quality / 100.0f, false);  

  32.        encoder.setJPEGEncodeParam(param);  

  33.        encoder.encode(thumbImage);  

  34.        out.close();  

  35.    }  




你可能感兴趣的:(java)