20 common Java Blocks

Source: Internet
Author: User
Tags java util

1. The strings are converted into integers.
String a = String. valueOf (2); // integer to numeric string
Int I = Integer. parseInt (a); // numeric string to an int

2. add content to the end of the file
BufferedWriter out = null;
Try {
Out = new BufferedWriter (new FileWriter ("filename", true ));
Out. write ("aString ");
} Catch (IOException e ){
// Error processing code

} Finally {
If (out! = Null ){
Out. close ();
}

}

3. Obtain the name of the current method.
String methodName = Thread. currentThread (). getStackTrace () [1]. getMethodName ();

4. Convert string to date
Java. util. Date = java. text. DateFormat. getDateInstance (). parse (date String );
Or:
SimpleDateFormat format = new SimpleDateFormat ("dd. MM. yyyy ");
Date date = format. parse (myString );

5. Use JDBC to connect to Oracle
Public class OracleJdbcTest
{
String driverClass = "oracle. jdbc. driver. OracleDriver ";

Connection con;

Public void init (FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException
{
Properties props = new Properties ();
Props. load (fs );
String url = props. getProperty ("db. url ");
String userName = props. getProperty ("db. user ");
String password = props. getProperty ("db. password ");
Class. forName (driverClass );

Con = DriverManager. getConnection (url, userName, password );
}

Public void fetch () throws SQLException, IOException
{
PreparedStatement ps = con. prepareStatement ("select SYSDATE from dual ");
ResultSet rs = ps.exe cuteQuery ();

While (rs. next ())
{
// Do the thing you do
}
Rs. close ();
Ps. close ();
}

Public static void main (String [] args)
{
OracleJdbcTest test = new OracleJdbcTest ();
Test. init ();
Test. fetch ();
}
}

6. Convert Java util. Date to SQL. Date.
Java. util. Date utilDate = new java. util. Date ();
Java. SQL. Date sqlDate = new java. SQL. Date (utilDate. getTime ());

7. Use NIO for Fast File copying
Public static void fileCopy (File in, File out)
Throws IOException
{
FileChannel inChannel = new FileInputStream (in). getChannel ();
FileChannel outChannel = new FileOutputStream (out). getChannel ();
Try
{
// InChannel. transferTo (0, inChannel. size (), outChannel); // original -- apparently has trouble copying large files on Windows

// Magic number for Windows, 64 Mb-32Kb)
Int maxCount = (64*1024*1024)-(32*1024 );
Long size = inChannel. size ();
Long position = 0;
While (position <size)
{
Position + = inChannel. transferTo (position, maxCount, outChannel );
}
}
Finally
{
If (inChannel! = Null)
{
InChannel. close ();
}
If (outChannel! = Null)
{
OutChannel. close ();
}
}
}

8. Create a thumbnail of the image
Private void createThumbnail (String filename, int thumbWidth, int thumbHeight, int quality, String outFilename)
Throws InterruptedException, FileNotFoundException, IOException
{
// Load image from filename
Image image = Toolkit. getdefatooltoolkit (). getImage (filename );
MediaTracker mediaTracker = new MediaTracker (new Container ());
MediaTracker. addImage (image, 0 );
MediaTracker. waitForID (0 );
// Use this to test for errors at this point: System. out. println (mediaTracker. isErrorAny ());

// Determine thumbnail size from WIDTH and HEIGHT
Double thumbRatio = (double) thumbWidth/(double) thumbHeight;
Int imageWidth = image. getWidth (null );
Int imageHeight = image. getHeight (null );
Double imageRatio = (double) imageWidth/(double) imageHeight;
If (thumbRatio <imageRatio ){
ThumbHeight = (int) (thumbWidth/imageRatio );
} Else {
ThumbWidth = (int) (thumbHeight * imageRatio );
}

// Draw original image to thumbnail image object and
// Scale it to the new size on-the-fly
BufferedImage thumbImage = new BufferedImage (thumbWidth, thumbHeight, BufferedImage. TYPE_INT_RGB );
Graphics2D graphics2D = thumbImage. createGraphics ();
Graphics2D. setRenderingHint (RenderingHints. KEY_INTERPOLATION, RenderingHints. VALUE_INTERPOLATION_BILINEAR );
Graphics2D. drawImage (image, 0, 0, thumbWidth, thumbHeight, null );

// Save thumbnail image to outFilename
BufferedOutputStream out = new BufferedOutputStream (new FileOutputStream (outFilename ));
Required imageencoder encoder = required codec. createJPEGEncoder (out );
Export encodeparam param = encoder. getDefaultJPEGEncodeParam (thumbImage );
Quality = Math. max (0, Math. min (quality, 100 ));
Param. setQuality (float) quality/100366f, false );
Encoder. setincluencodeparam (param );
Encoder. encode (thumbImage );
Out. close ();
}

9. Create data in JSON format
Import org. json. JSONObject;
...
...
JSONObject json = new JSONObject ();
Json. put ("city", "Mumbai ");
Json. put ("country", "India ");
...
String output = json. toString ();
...

10. Use iText JAR to generate a PDF file
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=. writable writer;

Public class GeneratePDF {

Public static void main (String [] args ){
Try {
OutputStream file = new FileOutputStream (new File ("C: testpipeline "));

Document document = new Document ();
Using writer. 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 ();
}
}
}

11. HTTP Proxy Settings
System. getProperties (). put ("http. proxyHost", "someProxyURL ");
System. getProperties (). put ("http. proxyPort", "someProxyPort ");
System. getProperties (). put ("http. proxyUser", "someUserName ");
System. getProperties (). put ("http. proxyPassword", "somePassword ");

12. Singleton example for a single instance
Public class SimpleSingleton {
Private static SimpleSingleton singleInstance = new SimpleSingleton ();

// Marking default constructor private
// To avoid direct instantiation.
Private SimpleSingleton (){
}

// Get instance for class SimpleSingleton
Public static SimpleSingleton getInstance (){

Return singleInstance;
}
}

Another implementation

Public enum SimpleSingleton {
INSTANCE;
Public void doSomething (){
}
}

// Call the method from Singleton:
SimpleSingleton. INSTANCE. doSomething ();

13. screen capture program
Import java. awt. Dimension;
Import java. awt. Rectangle;
Import java. awt. Robot;
Import java. awt. Toolkit;
Import java. awt. image. BufferedImage;
Import javax. imageio. ImageIO;
Import java. io. File;

...
Public void captureScreen (String fileName) throws Exception {

Dimension screenSize = Toolkit. getdefatooltoolkit (). getScreenSize ();
Rectangle screenRectangle = new Rectangle (screenSize );
Robot robot = new Robot ();
BufferedImage image = robot. createScreenCapture (screenRectangle );
ImageIO. write (image, "png", new File (fileName ));

}
...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.