`

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

    博客分类:
  • J2SE
阅读更多

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

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

view source
<embed id="highlighter_685098_clipboard" title="copy to clipboard" type="application/x-shockwave-flash" width="16" height="16" src="http://cocre.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter/scripts/clipboard.swf" lk_media="yes" lk_mediaid="lk_juiceapp_mediaPopup_1243315888969" allowscriptaccess="always" wmode="transparent" flashvars="highlighterId=highlighter_685098" menu="false"></embed>
print ?
1.    
2. String a = String.valueOf( 2 );   //integer to numeric string  
3. int i = Integer.parseInt(a); //numeric string to an int 


2. 向文件末尾添加内容

view source
<embed id="highlighter_886302_clipboard" title="copy to clipboard" type="application/x-shockwave-flash" width="16" height="16" src="http://cocre.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter/scripts/clipboard.swf" lk_media="yes" lk_mediaid="lk_juiceapp_mediaPopup_1243315888976" allowscriptaccess="always" wmode="transparent" flashvars="highlighterId=highlighter_886302" menu="false"></embed>
print ?
01.    
02. BufferedWriter out = null ;  
03. try {  
04.      out = new BufferedWriter( new FileWriter(”filename”, true ));  
05.      out.write(”aString”);  
06. } catch (IOException e) {  
07.      // error processing code  
08. } finally {  
09.      if (out != null ) {  
10.          out.close();  
11.      }  
12.

3. 得到当前方法的名字

view source
<embed id="highlighter_90532_clipboard" title="copy to clipboard" type="application/x-shockwave-flash" width="16" height="16" src="http://cocre.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter/scripts/clipboard.swf" lk_media="yes" lk_mediaid="lk_juiceapp_mediaPopup_1243315888980" allowscriptaccess="always" wmode="transparent" flashvars="highlighterId=highlighter_90532" menu="false"></embed>
print ?
1. String methodName = Thread.currentThread().getStackTrace()[ 1 ].getMethodName(); 

4. 转字符串到日期

view source
<embed id="highlighter_366714_clipboard" title="copy to clipboard" type="application/x-shockwave-flash" width="16" height="16" src="http://cocre.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter/scripts/clipboard.swf" lk_media="yes" lk_mediaid="lk_juiceapp_mediaPopup_1243315888984" allowscriptaccess="always" wmode="transparent" flashvars="highlighterId=highlighter_366714" menu="false"></embed>
print ?
1.    
2. java.util.Date = java.text.DateFormat.getDateInstance().parse(date String); 

或者是:

view source
<embed id="highlighter_544817_clipboard" title="copy to clipboard" type="application/x-shockwave-flash" width="16" height="16" src="http://cocre.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter/scripts/clipboard.swf" lk_media="yes" lk_mediaid="lk_juiceapp_mediaPopup_1243315888988" allowscriptaccess="always" wmode="transparent" flashvars="highlighterId=highlighter_544817" menu="false"></embed>
print ?
1.    
2. SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );  
3. Date date = format.parse( myString ); 

5. 使用JDBC链接Oracle

view source
<embed id="highlighter_694591_clipboard" title="copy to clipboard" type="application/x-shockwave-flash" width="16" height="16" src="http://cocre.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter/scripts/clipboard.swf" lk_media="yes" lk_mediaid="lk_juiceapp_mediaPopup_1243315888991" allowscriptaccess="always" wmode="transparent" flashvars="highlighterId=highlighter_694591" menu="false"></embed>
print ?
01. public class OracleJdbcTest  
02. {  
03.      String driverClass = "oracle.jdbc.driver.OracleDriver" ;  
04.    
05.      Connection con;  
06.    
07.      public void init(FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException  
08.      {  
09.          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

view source
<embed id="highlighter_65942_clipboard" title="copy to clipboard" type="application/x-shockwave-flash" width="16" height="16" src="http://cocre.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter/scripts/clipboard.swf" lk_media="yes" lk_mediaid="lk_juiceapp_mediaPopup_1243315888995" allowscriptaccess="always" wmode="transparent" flashvars="highlighterId=highlighter_65942" menu="false"></embed>
print ?
1. java.util.Date utilDate = new java.util.Date();  
2. java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime()); 

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

view source
<embed id="highlighter_484357_clipboard" title="copy to clipboard" type="application/x-shockwave-flash" width="16" height="16" src="http://cocre.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter/scripts/clipboard.swf" lk_media="yes" lk_mediaid="lk_juiceapp_mediaPopup_1243315888999" allowscriptaccess="always" wmode="transparent" flashvars="highlighterId=highlighter_484357" menu="false"></embed>
print ?
01. public static void fileCopy( File in, File out )  
02.              throws IOException  
03.      {  
04.          FileChannel inChannel = new FileInputStream( in ).getChannel();  
05.          FileChannel outChannel = new FileOutputStream( out ).getChannel();  
06.          try  
07.          {  
08. //          inChannel.transferTo(0, inChannel.size(), outChannel);      // original -- apparently has trouble copying large files on Windows  
09.    
10.              // magic number for Windows, 64Mb - 32Kb)  
11.              int maxCount = ( 64 * 1024 * 1024 ) - ( 32 * 1024 );  
12.              long size = inChannel.size();  
13.              long position = 0 ;  
14.              while ( position < size )  
15.              {  
16.                 position += inChannel.transferTo( position, maxCount, outChannel );  
17.              }  
18.          }  
19.          finally  
20.          {  
21.              if ( inChannel != null )  
22.              {  
23.                 inChannel.close();  
24.              }  
25.              if ( outChannel != null )  
26.              {  
27.                  outChannel.close();  
28.              }  
29.          }  
30.     

8. 创建图片的缩略图

view source
<embed id="highlighter_236268_clipboard" title="copy to clipboard" type="application/x-shockwave-flash" width="16" height="16" src="http://cocre.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter/scripts/clipboard.swf" lk_media="yes" lk_mediaid="lk_juiceapp_mediaPopup_1243315889003" allowscriptaccess="always" wmode="transparent" flashvars="highlighterId=highlighter_236268" menu="false"></embed>
print ?
01. private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename)  
02.          throws InterruptedException, FileNotFoundException, IOException  
03.      {  
04.          // load image from filename  
05.          Image image = Toolkit.getDefaultToolkit().getImage(filename);  
06.          MediaTracker mediaTracker = new MediaTracker( new Container());  
07.          mediaTracker.addImage(image, 0 );  
08.          mediaTracker.waitForID( 0 );  
09.          // 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, 0 , 0 , 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 格式的数据

请先阅读这篇文章 了解一些细节,
并下面这个JAR 文件:json-rpc-1.0.jar (75 kb)

view source
<embed id="highlighter_808034_clipboard" title="copy to clipboard" type="application/x-shockwave-flash" width="16" height="16" src="http://cocre.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter/scripts/clipboard.swf" lk_media="yes" lk_mediaid="lk_juiceapp_mediaPopup_1243315889007" allowscriptaccess="always" wmode="transparent" flashvars="highlighterId=highlighter_808034" menu="false"></embed>
print ?
01. import org.json.JSONObject;  
02. ...  
03. ...  
04. JSONObject json = new JSONObject();  
05. json.put( "city" , "Mumbai" );  
06. json.put( "country" , "India" );  
07. ...  
08. String output = json.toString();  
09. ... 

10. 使用iText JAR生成PDF

阅读这篇文章 了解更多细节

view source
<embed id="highlighter_651063_clipboard" title="copy to clipboard" type="application/x-shockwave-flash" width="16" height="16" src="http://cocre.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter/scripts/clipboard.swf" lk_media="yes" lk_mediaid="lk_juiceapp_mediaPopup_1243315889011" allowscriptaccess="always" wmode="transparent" flashvars="highlighterId=highlighter_651063" menu="false"></embed>
print ?
01.    
02. import java.io.File;  
03. import java.io.FileOutputStream;  
04. import java.io.OutputStream;  
05. import java.util.Date;  
06.    
07. import com.lowagie.text.Document;  
08. import com.lowagie.text.Paragraph;  
09. import com.lowagie.text.pdf.PdfWriter;  
10.    
11. public class GeneratePDF {  
12.    
13.      public static void main(String[] args) {  
14.          try {  
15.              OutputStream file = new FileOutputStream( new File( "C:\\Test.pdf" ));  
16.    
17.              Document document = new Document();  
18.              PdfWriter.getInstance(document, file);  
19.              document.open();  
20.              document.add( new Paragraph( "Hello Kiran" ));  
21.              document.add( new Paragraph( new Date().toString()));  
22.    
23.              document.close();  
24.              file.close();  
25.    
26.          } catch (Exception e) {  
27.    
28.              e.printStackTrace();  
29.          }  
30.      }  
31.

11. HTTP 代理设置

阅读这篇 文章 了解更多细节。

view source
<embed id="highlighter_44581_clipboard" title="copy to clipboard" type="application/x-shockwave-flash" width="16" height="16" src="http://cocre.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter/scripts/clipboard.swf" lk_media="yes" lk_mediaid="lk_juiceapp_mediaPopup_1243315889015" allowscriptaccess="always" wmode="transparent" flashvars="highlighterId=highlighter_44581" menu="false"></embed>
print ?
1.    
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" ); 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics