`

20个超级有用的Java程序片段(1)

    博客分类:
  • java
阅读更多

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

  Java代码

  1.   String a = String.valueOf(2);   //integer to numeric string
  2.   int i = Integer.parseInt(a); //numeric string to an int
复制代码
2. 向文件末尾添加内容

  Java代码
  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. 得到当前方法的名字

  Java代码

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

  4. 转字符串到日期

  Java代码
  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

  Java代码
  1.  public class OracleJdbcTest
  2.   {
  3.   String driverClass = "oracle.jdbc.driver.OracleDriver";
  4.   Connection con;
  5.   public void 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.   public void 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.   public static void main(String[] args)
  27.   {
  28.   OracleJdbcTest test = new OracleJdbcTest();
  29.   test.init();
  30.   test.fetch();
  31.   }
  32.   }
复制代码
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.  public static void 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. 创建图片的缩略图

  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.   // 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.   }
复制代码
9. 创建 JSON 格式的数据

  Java代码
  1.  import org.json.JSONObject;
  2.   ...
  3.   ...
  4.   JSONObject json = new JSONObject();
  5.   json.put("city", "Mumbai");
  6.   json.put("country", "India");
  7.   ...
  8.   String output = json.toString();
  9.   ...
复制代码
10. 使用iText JAR生成PDF

  Java代码

  阅读这篇文章 了解更多细节
 import java.io.File;
  import java.io.FileOutputStream;
  import java.io.OutputStream;
  import java.util.Date;
  import com.lowagie.text.Document;
  import com.lowagie.text.Paragraph;
  import com.lowagie.text.pdf.PdfWriter;
  public class GeneratePDF {
  public static void main(String[] args) {
  try {
  OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
  Document document = new Document();
  PdfWriter.getInstance(document, file);
  document.open();
  document.add(new Paragraph("Hello Kiran"));
  document.add(new Paragraph(new Date().toString()));
  document.close();
  file.close();
  } catch (Exception e) {
  e.printStackTrace();
  }
  }
  }
[/code]
11. HTTP 代理设置

  Java代码
  1. System.getProperties().put("http.proxyHost", "someProxyURL");
  2.   System.getProperties().put("http.proxyPort", "someProxyPort");
  3.   System.getProperties().put("http.proxyUser", "someUserName");
  4.   System.getProperties().put("http.proxyPassword", "somePassword");
复制代码
12. 单实例Singleton 示例

  Java代码
  1.  public class SimpleSingleton {
  2.   private static SimpleSingleton singleInstance =  new SimpleSingleton();
  3.   //Marking default constructor private
  4.   //to avoid direct instantiation.
  5.   private SimpleSingleton() {
  6.   }
  7.   //Get instance for class SimpleSingleton
  8.   public static SimpleSingleton getInstance() {
  9.   return singleInstance;
  10.   }
  11.   }
复制代码
另一种实现
  1.  public enum SimpleSingleton {
  2.   INSTANCE;
  3.   public void doSomething() {
  4.   }
  5.   }
  6.   //Call the method from Singleton:
  7.   SimpleSingleton.INSTANCE.doSomething();
复制代码

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics