java程序片_20个非常有用的Java程序片段(一)

下面是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.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

1.java.util.Date utilDate = new java.util.Date();

2.java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

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

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.

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 

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.创建图片的缩略图

1.private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename)

2.throws InterruptedException, FileNotFoundException, IOException

3.{

4.// load p_w_picpath from filename

5.Image p_w_picpath = Toolkit.getDefaultToolkit().getImage(filename);

6.MediaTracker mediaTracker = new MediaTracker(new Container());

7.mediaTracker.addImage(p_w_picpath, 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 p_w_picpathWidth = p_w_picpath.getWidth(null);

14.int p_w_picpathHeight = p_w_picpath.getHeight(null);

15.double p_w_picpathRatio = (double)p_w_picpathWidth / (double)p_w_picpathHeight;

16.if (thumbRatio 

17.thumbHeight = (int)(thumbWidth / p_w_picpathRatio);

18.} else {

19.thumbWidth = (int)(thumbHeight * p_w_picpathRatio);

20.}

21.

22.// draw original p_w_picpath to thumbnail p_w_picpath 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(p_w_picpath, 0, 0, thumbWidth, thumbHeight, null);

28.

29.// save thumbnail p_w_picpath 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 格式的数据1.importorg.json.JSONObject;2....3....4.JSONObject json =newJSONObject();5.json.put("city","Mumbai");6.json.put("country","India");7....8.String output = json.toString();9....

10.使用iTextJAR生成PDF

阅读这篇文章了解更多细节1.importjava.io.File;2.importjava.io.FileOutputStream;3.importjava.io.OutputStream;4.importjava.util.Date;5.6.importcom.lowagie.text.Document;7.importcom.lowagie.text.Paragraph;8.importcom.lowagie.text.pdf.PdfWriter;9.10.publicclassGeneratePDF {11.12.publicstaticvoidmain(String[] args) {13.try{14.OutputStream file =newFileOutputStream(newFile("C:\\Test.pdf"));15.16.Document document =newDocument();17.PdfWriter.getInstance(document, file);18.document.open();19.document.add(newParagraph("Hello Kiran"));20.document.add(newParagraph(newDate().toString()));21.22.document.close();23.file.close();24.25.}catch(Exception e) {26.27.e.printStackTrace();28.}29.}30.}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值