常用的Java代码段有哪些

冬芳大大_4368

冬芳大大_4368

2021-03-17

16906人浏览

原创

常用的Java代码段有:1、字符串有整型的相互转换;2、向文件末尾添加内容;3、得到当前方法的名字;4、转字符串到日期;5、使用JDBC链接Oracle。

本教程操作环境:windows7系统、java10版,DELL G3电脑。

常用的Java代码段有:

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

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

2. 向文件末尾添加内容

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. 得到当前方法的名字

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

4. 转字符串到日期

java.util.Date = java.text.DateFormat.getDateInstance().parse(date String);

或者是:

SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );  
Date date = format.parse( myString );

5. 使用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();  
    }  
}

6. 把 Java util.Date 转成 sql.Date

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

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

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, 64Mb - 32Kb)  
            int maxCount = (64 * 1024 * 1024) - (32 * 1024);  
            long size = inChannel.size();  
            long position = 0;  
            while ( position <p>8. 创建图片的缩略图</p><pre class="brush:php;toolbar:false">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 <p>9. 创建 JSON 格式的数据</p><p>请先阅读这篇文章 了解一些细节,</p><p>并下面这个JAR 文件:json-rpc-1.0.jar (75 kb)</p><pre class="brush:php;toolbar:false">import org.json.JSONObject;  
...  
...  
JSONObject json = new JSONObject();  
json.put("city", "Mumbai");  
json.put("country", "India");  
...  
String output = json.toString();  
...

10. 使用iText JAR生成PDF

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

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

相关免费学习推荐:java基础教程

Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南

java速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
PHP 8.6报错排查指南
PHP 8.6报错排查指南

错误处理和日志记录是PHP应用定位故障、追踪运行状态的重要手段。本专题结合PHP 8.6介绍从本地调试到线上日志管理的常用做法,说明怎样保留有用的错误信息,同时控制堆栈和敏感数据的暴露,便于在问题发生后找到排查线索。

2026.12.02

20

8

PHP 8.6日期计算教程
PHP 8.6日期计算教程

日期和时间既用于页面显示,也关系到统计结果与业务规则是否准确。本专题结合PHP 8.6介绍日期计算和时区转换的常用方法,讲清日期、时间点与显示格式的区别,遇到月末、跨年或夏令时等情况时,能按明确的规则处理。

2026.12.02

20

8

PHP 8.6 cURL用法详解
PHP 8.6 cURL用法详解

cURL可用于PHP项目调用外部接口和传输文件,连接方式与认证配置会直接影响请求结果。本专题整理PHP 8.6中常见的cURL用法,说明不同连接环境下的配置思路,帮助理解证书、身份认证和请求结果之间的关系,也为调用失败时的排查提供参考。

2026.12.02

0

8

Watermill消息发布订阅实战
Watermill消息发布订阅实战

本专题聚焦Watermill的消息发布与订阅,拆解Publisher接口、Topic指定、Ack/Nack确认与批量发送,说明元数据传递、载荷序列化、消费者组与幂等消费,并整理消息重复、乱序与丢失的排查路径。

2026.12.01

20

15

Watermill安装配置指南
Watermill安装配置指南

本专题围绕Watermill的安装与快速上手展开,讲清依赖拉取、Go channel本地总线与RabbitMQ最小示例,说明消息发布订阅的调用流程、Context传递与容器网络配置,并整理依赖冲突和连接超时的处理办法。

2026.12.01

20

15

Watermill消息入门教程合集
Watermill消息入门教程合集

本专题整理Watermill的入门知识,从工具定位、核心概念到本地跑通第一条消息,讲清消息对象、目录结构与配置管理的用法,并对比其他消息库的差异,帮助Go开发者建立事件驱动的整体认知。

2026.12.01

20

15

Jest Mock 函数怎么用
Jest Mock 函数怎么用

Jest Mock 函数怎么用?本专题整理 jest.fn() 创建模拟函数、调用次数和参数断言、jest.mock() 模块替换、Spy 监视以及清理 Mock 状态等相关文章,帮助你隔离依赖并编写稳定测试。

2026.11.30

20

10

Jest 如何测试异步代码
Jest 如何测试异步代码

Jest 如何测试异步代码?本专题整理 Promise 返回值、async/await、resolves 与 rejects 断言、异步模块和定时器测试等文章,帮助你正确等待异步任务并检查成功或失败结果。

2026.11.30

0

10

Jest 的 test() 和 expect() 怎么用
Jest 的 test() 和 expect() 怎么用

Jest 的 test() 和 expect() 怎么用?本专题汇集测试用例编写、基础断言、toBe 与 toEqual 的区别,以及对象和异常断言等相关文章,帮助你掌握 Jest 单元测试的基本写法。

2026.11.30

0

10

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
热门推荐
/
最新课程
phpStudy极速入门视频教程
phpStudy极速入门视频教程

共6课时 | 54.8万人学习

独孤九贱(4)_PHP视频教程
独孤九贱(4)_PHP视频教程

共89课时 | 134.6万人学习