1.字符串-整型相互转换

String s = String.valueOf(2);
int a = Integer.parseInt(s);

2.向文件末尾添加内容

BufferedWriter bufferedWrite = null;
try {
bufferedWrite = new BufferedWriter(new FileWriter("C:\\Users\\Administrator\\Desktop\\2.txt",true));
bufferedWrite.write("hello java file writer ");
} catch(IOException e) {
e.printStackTrace();
} finally {
if ( bufferedWrite != null ) {
bufferedWrite.close();
}
}

3.得到当前方法的名字

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

4.转字符串到日期

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
String d = "2008-07-10 20:23:30";
try {
Date date = simpleDateFormat.parse(d);
System.out.println(date.toString());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

5.使用JDBC连接MySQL

package com.fpc.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties; public class MySqlJdbcTest {
private String driverClass = "com.mysql.jdbc.Driver";
private Connection connection; //connection
public void init(FileInputStream fs) throws IOException, ClassNotFoundException, SQLException {
Properties properties = new Properties();
properties.load(fs);
String url = properties.getProperty("url");
String username = properties.getProperty("name");
String password = properties.getProperty("password");
Class.forName(driverClass);
connection = DriverManager.getConnection(url,username,password);
} //fetch
public void fetch () throws SQLException {
String sql = "select * from student";
PreparedStatement ps = connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while ( rs.next() ) {
System.out.println(rs.getString("s_name"));
}
rs.close();
ps.close();
}
public static void main(String[] args) throws ClassNotFoundException, IOException, SQLException {
MySqlJdbcTest test = new MySqlJdbcTest();
File file = new File("C:\\Users\\Administrator\\Desktop\\db.properties");
FileInputStream fs = new FileInputStream(file);
test.init(fs);
test.fetch();
}
}

6.把Java.util.Date转成Java.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();
//magic number for windows,64MB -32Kb
int maxCount = (64*1024*1024) - (32*1024);
long size = inChannel.size();
int position = 0;
while ( position < size ) {
position += inChannel.transferTo(position, maxCount, outChannel);
}
if ( inChannel != null ) {
inChannel.close();
}
if ( outChannel != null ) {
outChannel.close();
}
}

8.创建JSON格式的数据

下载jar文件 json-rpc-1.0.jar

        JSONObject json = new JSONObject();
json.put("name","fpc");
json.put("age", 22);
String str = json.toString();

9.使用iText JAR生成PDF

Download itextpdf-5.4.1.jar

public static void main(String[] args) throws IOException, DocumentException{
OutputStream file = new FileOutputStream(new File("C:\\Users\\Administrator\\Desktop\\test.pdf"));
Document document = new Document();
PdfWriter.getInstance(document, file);
document.open();
document.add(new Paragraph("Hello Fpc"));
document.add(new Paragraph(new Date().toString()));
document.close();
file.close();
}

10.抓屏程序

public void captureScreen(String fileName) throws IOException, AWTException {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
ImageIO.write(image, "png", new File(fileName));
}

11.解析/读取XML文件

package com.fpc.Test;

import java.io.File;
import java.io.IOException; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException; public class XMLParser {
public void getAllUserNames(String fileName) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File file = new File(fileName); if ( file.exists() ) {
Document doc = db.parse(file);
Element docElement = doc.getDocumentElement(); //Print root element of the document
System.out.println("Root element of the document: " + docElement.getNodeName()); NodeList studentList = docElement.getElementsByTagName("student");
//Print total student elements in document
System.out.println("Total students: " + studentList.getLength()); if ( studentList != null && studentList.getLength() > 0 ) {
for ( int i = 0 ; i < studentList.getLength() ; i++ ) {
Node node = studentList.item(i);
if ( node.getNodeType() == Node.ELEMENT_NODE ) {
System.out.println("**********************************");
Element element = (Element) node;
NodeList nodeList = element.getElementsByTagName("name");
System.out.println("Name : " + nodeList.item(0).getChildNodes().item(0).getNodeValue()); nodeList = element.getElementsByTagName("grade");
System.out.println("Grade : " + nodeList.item(0).getChildNodes().item(0).getNodeValue()); nodeList = element.getElementsByTagName("age");
System.out.println("Age : " + nodeList.item(0).getChildNodes().item(0).getNodeValue());
} else {
System.exit(1);
}
}
}
}
} public static void main( String[] args ) throws ParserConfigurationException, SAXException, IOException {
XMLParser xmlparser = new XMLParser();
xmlparser.getAllUserNames("C:\\Users\\Administrator\\Desktop\\test.xml");
}
}

12.把Array转成Map

commons-lang3-3.7.jar

public static void main( String[] args )  {
String[][] countries = { { "United States", "New York" }, { "United Kingdom", "London" },
{ "Netherland", "Amsterdam" }, { "Japan", "Tokyo" }, { "France", "Paris" } };
Map<Object, Object> countriesCapitical = ArrayUtils.toMap(countries);
//traverse
for ( Map.Entry<Object, Object> entry : countriesCapitical.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
} }

Java-工程中常用的程序片段的更多相关文章

  1. JAVA项目中常用的异常处理情况总结

    JAVA项目中常用的异常知识点总结 1. java.lang.nullpointerexception这个异常大家肯定都经常遇到,异常的解释是"程序遇上了空指针",简单地说就是调用 ...

  2. JAVA项目中常用的异常知识点总结

    JAVA项目中常用的异常知识点总结 1. java.lang.nullpointerexception这个异常大家肯定都经常遇到,异常的解释是"程序遇上了空指针",简单地说就是调用 ...

  3. Java开发中常用jar包整理及使用

    本文整理了我自己在Java开发中常用的jar包以及常用的API记录. <!-- https://mvnrepository.com/artifact/org.apache.commons/com ...

  4. Log4j在Java工程中使用方法

    Eclipse新建Java工程,工程目录如下 1.下载log4j的Jar包,在Java工程下新建lib文件夹,将jar包拷贝到此文件夹,并将其加入到路径中,即:Jar包上右键——Build Path— ...

  5. java工程中不能存在多个数据库连接jar包

    java工程中不能存在多个数据库连接jar包 比如存在mysql-java-connector.jar的,放入mssqlserver.jar就会产生冲突.只能存在一个类型的jar包.

  6. 在java工程中导入jar包的注意事项

    在java工程中导入jar包后一定要bulid path,不然jar包不可以用.而在java web工程中导入jar包后可以不builld path,但最好builld path.

  7. 【技巧】Java工程中的Debug信息分级输出接口

    也许本文的标题你们没咋看懂.但是,本文将带大家领略输出调试的威力. 灵感来源 说到灵感,其实是源于笔者在修复服务器的ssh故障时的一个发现. 这个学期初,同袍(容我来一波广告产品页面,同袍官网)原服务 ...

  8. 【技巧】Java工程中的Debug信息分级输出接口及部署模式

    也许本文的标题你们没咋看懂.但是,本文将带大家领略输出调试的威力. 灵感来源 说到灵感,其实是源于笔者在修复服务器的ssh故障时的一个发现. 这个学期初,同袍(容我来一波广告产品页面,同袍官网)原服务 ...

  9. java工程中的.classpathaaaaaaaaaaaaaaaa<转载>

    第一部分:classpath是系统的环境变量,就是说JVM加载类的时候要按这个路径下去找,当然这个路径下可以有jar包,那么就是jar包里所有的class. eclipse build path是ec ...

随机推荐

  1. [Linux]read/write和fread/fwrite有什么区别

    转自:http://blog.csdn.net/xiaofei0859/article/details/51145051 二者都是对文件进行操作,那么二者有什么区别,用的时候该如何选择呢? 1. 区别 ...

  2. etl工具,kettle实现循环

    Kettle是一款国外开源的ETL工具,纯Java编写,可以在Window.Linux.Unix上运行,绿色无需安装,数据抽取高效稳定. 业务模型: 在关系型数据库中有张很大的数据存储表,被设计成奇偶 ...

  3. Css三栏布局自适应实现几种方法

    Css三栏布局自适应实现几种方法 自适应实现方法我们可以从三个方法来做,一个是绝对定位 ,自身浮动法 和margin负值法了,下面我们一起来看看这三个例子吧,希望例子能帮助到各位同学. 绝对定位法三栏 ...

  4. noip2014滚粗记

    滚粗了..伤心. day0:和baba一起去,但是整天都是下雨啊好不爽,鞋子都湿了啊好不爽,注定是要滚粗?在火车站等了1h后上动车走人...在此期间我还天真的认为火车站的wifi可以被我给破解然后上网 ...

  5. TCP通信服务端及客户端代码

    Java TCP通信使用的是Socket(客服端)和ServerSocket(服务端),具体代码如下. server端代码: import java.io.BufferedReader; import ...

  6. ip地址查询系统和CMD查询的结果不一样

    由于cmd输入 ipconfig查看的IP是局域网内网IP,而用ip地址查看器查看是公网上网的ip地址.所以不一样. 查询内网ip: windows系统: 开始--运行--cmd,命令行输入: ipc ...

  7. AWS系列-EC2实例选择镜像

    Centos Ubuntu Redhat 打开EC2控制台,点击启动实例,选择AWS Marketplace Centos.org说明为centos官网镜像 如下图,这种镜像是收费的镜像 Ubuntu ...

  8. iOS开发之-- 抢购、距活动结束,剩余时间倒计时

    因为没有时间去着重研究过这个东西,只是知道大体上的逻辑,就是两个时间才行比对,具体的实现也是参考别人的写的方法, 只是做个记录,有时间会好好看看这个东西,具体代码如下: /** * 倒计时 * * @ ...

  9. 教你在Ubuntu上体验Mac风格

    导读 老实说,我是个狂热的 Ubuntu 迷,我喜欢 Ubuntu 默认的 Unity 主题样式外观.此外,还有很多关于 Ubuntu 14.04 的漂亮图标主题样式 可用来美化默认的外观.但正如我上 ...

  10. poj 1386

    Play on Words Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 11312   Accepted: 3862 De ...