Java常用代码

 

1.String型转换成int型与int型转换成String型

View Code
1 //integer to numeric string
2  String a = String.valueOf(2);
3
4  //numeric string to an int
5  int i = Integer.parseInt(a);

 

2.向Java文件中添加文本

View Code
1 BufferedWriter out = null;
2  try{
3 out = new BufferedWriter(new FileWriter(”filename”, true));
4 out.write(”aString”);
5 }
6  catch (IOException e) { /* error processing code */ }
7  finally {
8 if (out != null) {
9 out.close();
10 }
11 }

 

3.获取Java正在调用的方法名

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

 

4.在Java中将String型转换为Date型

View Code
1 //method one
2  java.util.Date = java.text.DateFormat.getDateInstance().parse(date String);
3
4  //method two
5  SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
6 Date date = format.parse( myString );

 

5.通过JDBC连接数据库

View Code
1 public class oraclejdbcTest {
2 String driverClass = "oracle.jdbc.driver.oracleDriver";
3 Connection con;
4 public void init(FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException {
5 Properties props = new Properties();
6 props.load(fs);
7 String url = props.getProperty("db.url");
8 String userName = props.getProperty("db.user");
9 String password = props.getProperty("db.password");
10 Class.forName(driverClass);
11 con=DriverManager.getConnection(url, userName, password);
12 }
13 public void fetch() throws SQLException, IOException{
14 PreparedStatement ps = con.prepareStatement("select SYSDATE from dual");
15 ResultSet rs = ps.executeQuery();
16 while (rs.next()) {
17 // do the thing you do
18   }
19 rs.close();
20 ps.close();
21 }
22 Public static void main(String[] args) {
23 oraclejdbcTest test = new oraclejdbcTest();
24 test.init(); test.fetch();
25 }
26 }

 

 

6.java中的util.Date转换成sql.Date这一片段显示如何将一个java util Date转换成sql Date用于数据库

View Code
1 java.util.Date utilDate = new java.util.Date();
2 java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

 

7.使用NIO快速复制Java文件

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

 

8.在Java中使用缩略图

View Code
1 private void createThumbnail(String filename, int thumbWidth,int thumbHeight, int quality, String outFilename) throws InterruptedException, FileNotFoundException, IOException {
2 // load image fromfilename
3 Image image = Toolkit.getDefaultToolkit().getImage(filename);
4 MediaTracker mediaTracker = new MediaTracker(new Container());
5 mediaTracker.addImage(image, 0);
6 mediaTracker.waitForID(0);
7 // use this to test for errors at this point:
8 System.out.println(mediaTracker.isErrorAny());
9 // determine thumbnail size fromWIDTH and HEIGHT
10 Double thumbRatio = (double)thumbWidth / (double)thumbHeight;
11 int imageWidth = image.getWidth(null);
12 int imageHeight = image.getHeight(null);
13 double imageRatio = (double)imageWidth / (double)imageHeight;
14 if (thumbRatio < imageRatio){
15 thumbHeight = (int)(thumbWidth / imageRatio);
16 } else {
17 thumbWidth =(int)(thumbHeight * imageRatio);
18 }
19 // draw original image to thumbnail image object and
20 //scale it to the new size on-the-fly
21 BufferedImage thumbImage = newBufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
22 Graphics2D graphics2D = thumbImage.createGraphics();
23 graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
24 graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
25 // save thumbnail image to outFilename BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream(outFilename));
26 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
27 JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
28 quality = Math.max(0, Math.min(quality, 100));
29 param.setQuality((float)quality / 100.0f, false);
30 encoder.setJPEGEncodeParam(param);
31 encoder.encode(thumbImage);
32 out.close();
33 }

 

9.在Java中使用iText JAR打开PDF文

View Code
1 //Read this article for more details.
2 import java.io.File;
3 import java.io.FileOutputStream;
4 import java.io.OutputStream;
5 import java.util.Date;
6 import com.lowagie.text.Document;
7 import com.lowagie.text.Paragraph;
8 import com.lowagie.text.pdf.PdfWriter;
9 public class GeneratePDF{
10 public static void main(String[] args) {
11 try {
12 OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
13 Document document = new Document();
14 PdfWriter.getInstance(document, file);
15 document.open();
16 document.add(new Paragraph("Hello Kiran"));
17 document.add(new Paragraph(new Date().toString()));
18 document.close(); file.close();
19 } catch(Exception e) {
20 e.printStackTrace();
21 }
22 }
23 }

 

10.在Java上做屏幕截

View Code
1 //Read this article for more details.
2 import java.awt.Dimension;
3 import java.awt.Rectangle;
4 import java.awt.Robot;
5 import java.awt.Toolkit;
6 import java.awt.image.BufferedImage;
7 import javax.imageio.ImageIO;
8 import java.io.File;
9
10 public void captureScreen(String fileName) throws Exception {
11 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
12 Rectangle screenRectangle = new Rectangle(screenSize);
13 Robot robot = new Robot();
14 BufferedImage image = robot.createScreenCapture(screenRectangle);
15 ImageIO.write(image, "png", new File(fileName));
16 }

 

11.接收键盘输入

View Code
1 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

posted on 2011-03-27 13:27  五月十七  阅读(241)  评论(0)    收藏  举报

导航