1. 把Strings转换成int和把int转换成String

String a = String.valueOf(2); //integer to numeric string  
int i = Integer.parseInt(a); //numeric string to an int 
String a = String.valueOf(2);   //integer to numeric string
int i = Integer.parseInt(a); //numeric string to anint

2. 向Java文件中添加文本

Updated: Thanks Simone for pointing to exception. I have changed the code. 
BufferedWriter ut = null;  
try {  
out = new BufferedWriter(new FileWriter(”filename”, true));  
out.write(”aString”);  
} catch (IOException e) {  
// error processing code  
} finally {  
if (out != null) {  
out.close();  
}  
}

BufferedWriter ut = 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. 获取Java现在正调用的方法名

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

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

java.util.Date = java.text.DateFormat.getDateInstance().parse(date String); 
java.util.Date = java.text.DateFormat.getDateInstance().parse(date String);or 
SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );  
Date date = format.parse( myString ); 
SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );
Date date= format.parse( myString );

5. 通过Java JDBC链接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.executeQuery();

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();  
}  
}

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.executeQuery();
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.将Java中的util.Date转换成sql.Date
这一片段显示如何将一个java util Date转换成sql Date用于数据库

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

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

public static void fileCopy( File in, File out )  
throws IOException  
{  
FileChannel inChannel = new FileInputStream( in ).getChannel();  
FileChannel utChannel = new FileOutputStream( out ).getChannel();  
try 
{  
//          inChannel.transferTo(0, inChannel.size(), outChannel);      // original
-- apparently has trouble copying large files on Windows

// magic number for Windows, 64Mb - 32Kb)  
int maxCount = (64 * 1024 * 1024) - (32 * 1024);  
long size = inChannel.size();  
long position = 0;  
while ( position < size )  
{  
&nbsp; position += inChannel.transferTo( position, maxCount, outChannel );

}  
}  
finally 
{  
if ( inChannel != null )  
{  
&nbsp; inChannel.close();  
}  
if ( outChannel != null )  
{  
&nbsp;  outChannel.close();  
}  
}  
}

public static void fileCopy( File in, File out )
throws IOException
{
FileChannel inChannel = new FileInputStream( in ).getChannel();
FileChannel utChannel = new FileOutputStream( out ).getChannel();
try
{
//          inChannel.transferTo(0, inChannel.size(), outChannel);      // original
-- apparently has trouble copying large files on Windows
// magic number for Windows, 64Mb - 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. 在Java中创建缩略图

private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int
quality, String outFilename)  
throws InterruptedException, FileNotFoundException, IOException  
{  
// load image from filename  
Image image = Toolkit.getDefaultToolkit().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 ut = new BufferedOutputStream(new FileOutputStream
(outFilename));  
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);  
quality = Math.max(0, Math.min(quality, 100));  
param.setQuality((float)quality / 100.0f, false);  
encoder.setJPEGEncodeParam(param);  
encoder.encode(thumbImage);  
out.close();  
}

private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int
quality, String outFilename)
throws InterruptedException, FileNotFoundException, IOException
{
// load image from filename
Image image = Toolkit.getDefaultToolkit().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 ut = new BufferedOutputStream(new
FileOutputStream(outFilename));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam
(thumbImage);
quality = Math.max(0, Math.min(quality, 100));
param.setQuality((float)quality / 100.0f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(thumbImage);
out.close();
}

9. 在Java中创建JSON数据

Read this article for more details.
Download JAR file json-rpc-1.0.jar (75 kb)

import org.json.JSONObject;  
...  
...  
JSONObject json = new JSONObject();  
json.put("city", "Mumbai");  
json.put("country", "India");  
...  
String utput = json.toString();  
...

import org.json.JSONObject;
...
...
JSONObject json = new JSONObject();
json.put("city", "Mumbai");
json.put("country", "India");
...
String utput = json.toString();
...
10. 在Java中使用iText JAR打开PDF

Read this article for more details.

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();  
}  
}  
}

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();
}
}
}

转载于:https://blog.51cto.com/apprentice/1360617

20个开发人员非常有用的Java功能代码(一)相关推荐

  1. 20个开发人员非常有用的Java功能代码(二)

    11. 在Java上的HTTP代理设置 System.getProperties().put("http.proxyHost", "someProxyURL") ...

  2. java 开发人员工具_每个Java开发人员都应该知道的10个基本工具

    java 开发人员工具 大家好,我们已经到了2019年的第二个月,我相信你们所有人都已经制定了关于2019年学习以及如何实现这些目标的目标. 我一直在撰写一系列文章,为您提供一些知识,使您可以学习和改 ...

  3. 开发人员必备:微软发布示例代码浏览器 (Sample Browser) 第五版,让您尽享3500个示例代码...

    今天早上,微软一站式示例代码库 携手MSDN和微软创新空间 正式发布了示例代码浏览器(Sample Browser)第五版.这是继去年10月第四版发布以来的一次重大升级.有了它,3500多高质量示例代 ...

  4. 善于使用F12开发人员工具来快速调试js代码

    使用F12工具快速调试扣出的js代码 前言 该文章讲述,如何善于使用F12开发人员工具来高效的调试代码,这里以360极速浏览器为案例,并且推荐使用这款浏览器,非常高效. 一.打开浏览器,打开F12开发 ...

  5. 适用于Java开发人员的Elasticsearch:Java的Elasticsearch

    本文是我们学院课程的一部分,该课程的标题为Java开发人员的Elasticsearch教程 . 在本课程中,我们提供了一系列教程,以便您可以开发自己的基于Elasticsearch的应用程序. 我们涵 ...

  6. web前端代码开发工具_Web开发人员的有用代码比较工具

    许多不同语言的开发人员都有着共同的成长难题. 冗长的源代码将在开发人员的整个职业生涯中成为一个棘手的问题,但是考虑较少的问题是编译和合并来自同一源的两个或更多副本的编辑. 幸运的是,对于这种情况,有非 ...

  7. 字符串排序java_开发人员是如何使用Java进行排序?

    在分析大量开源Java项目的源代码时,我发现Java开发人员经常以两种方式进行排序.一种使用的sort()是Collections或的方法,Arrays另一种使用的是排序的数据结构,例如TreeMap ...

  8. 目前Java开发人员需求大吗 Java就业方向是什么

    目前Java开发人员需求大吗?Java就业方向是什么?Java作为一门经典开发语言,经历过高速发展期,也经历过低谷,仍占据编程界的大片江山.数据显示,我国软件开发人才非常缺乏,其中对Java软件工程师 ...

  9. 一名优秀的开发人员,空闲时间会敲代码吗

    原网页:Do I Need to Code in My Free Time to Be a Good Developer? 作者:Maxim Chechenev "只有在空闲时间也敲代码,才 ...

  10. 献给 Python 开发人员的 25 个最佳 GitHub 代码库!

    以下为译文: 根据2020年StackOverflow开发者调查报告,Python是世界上最受欢迎的语言之一,排名仅次于Rust和TypeScript.更令人惊讶的是,Python是开发人员最想尝试的 ...

最新文章

  1. vscode创建工作区_区领导调研工业区高楼村乡村振兴示范村创建工作!
  2. 全国成人计算机考试题,成人计算机考试试题.docx
  3. 安装python3.6.1_CentOS 7 安装Python3.6.1 多版本共存
  4. 国内哪里培训python比较好-python培训机构怎么选择?哪家比较靠谱?
  5. 华为p20支持手机云闪付吗_华为官宣7款旗舰支持升级EMUI10.132系统,你的手机有份吗?...
  6. ASP.NET MVC 2 学习笔记二: 表单的灵活提交
  7. C#中HTML和UBB互相转换的代码
  8. Combating Adversarial Misspellings with Robust Word Recognition
  9. 关于升级到win10后的网络问题
  10. 【图像压缩】基于matlab DCT变换图像压缩【含Matlab源码 804期】
  11. H264/AVC-NALU解析
  12. python播放音乐同步歌词_Python点阵字玩转动态歌词
  13. 1222-周一开盘红红火火大涨的一天。EG,PVC,沪铜,国际铜,纯碱涨停
  14. 在MySQL中group by 是什么意思
  15. Power Pivot数据建模与数据汇总分析
  16. 高德地图获取用户当前位置
  17. Mybatis官方网站
  18. JDK异常处理No appropriate protocol
  19. 城科软件协会官网正式上线
  20. pet shop 4.0架构信息-转

热门文章

  1. Kubernetes API的版本控制,分组,对象,访问控制
  2. JAVA日常优化---Guava缓存玩耍异步刷新
  3. 括号里面一个上面一个数下面一个数符号怎么打?/ 概率论组合符号怎么打?
  4. 能力提升综合题单 Part 8.8 二分图
  5. 常问的数据结构与算法
  6. centos7 mysql5.7.2_Install mysql5.7 on centos7.2
  7. 华为p10点击六下android,要被口水喷到死机的华为P10 你用的怎么样
  8. java朴素贝叶斯_java实现朴素贝叶斯算法
  9. 第 7 章 Neutron - 079 - 在 ML2 中 enable local network
  10. Office - Excel 2013