原文:Mkyong
如何在 Hibernate 中配置 DBCP 连接池
Note
Due to bugs in the old DBCP code, Hibernate is no longer maintain DBCP-based connection provider, read this Hibernate thread.
现在,阿帕奇 DBCP 回到了积极的开发中,许多 bug 被修复,现在更加稳定了。即使 Hibernate 没有像 C3P0 和 Proxool 这样的连接提供者,但是你仍然可以很容易地配置它。
在本教程中,我们将向您展示如何集成 Apache DBCP 连接池和 Hibernate 框架。
1.去拿 DBCP 罐
要集成 DBCP 和 Hibernate,你需要 commons-dbcp.jar 和 commons-pool-1.5.4.jar 。
文件:pom.xml
<project ...>
<repositories>
<repository>
<id>JBoss repository</id>
<url>http://repository.jboss.org/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.3.Final</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
</project>
2.DBCPConnectionProvider
要将 DBCP 与 Hibernate 集成,需要创建一个" DBCPConnectionProvider "类,参见这篇文章。
文件:DBCPConnectionProvider.java
package com.mkyong.util;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.hibernate.HibernateException;
import org.hibernate.cfg.Environment;
import org.hibernate.connection.ConnectionProvider;
import org.hibernate.connection.ConnectionProviderFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DBCPConnectionProvider implements ConnectionProvider {
private static final Logger log = LoggerFactory
.getLogger(DBCPConnectionProvider.class);
private static final String PREFIX = "hibernate.dbcp.";
private BasicDataSource ds;
// Old Environment property for backward-compatibility (property removed in
// Hibernate3)
private static final String DBCP_PS_MAXACTIVE = "hibernate.dbcp.ps.maxActive";
// Property doesn't exists in Hibernate2
private static final String AUTOCOMMIT = "hibernate.connection.autocommit";
public void configure(Properties props) throws HibernateException {
try {
log.debug("Configure DBCPConnectionProvider");
// DBCP properties used to create the BasicDataSource
Properties dbcpProperties = new Properties();
// DriverClass & url
String jdbcDriverClass = props.getProperty(Environment.DRIVER);
String jdbcUrl = props.getProperty(Environment.URL);
dbcpProperties.put("driverClassName", jdbcDriverClass);
dbcpProperties.put("url", jdbcUrl);
// Username / password
String username = props.getProperty(Environment.USER);
String password = props.getProperty(Environment.PASS);
dbcpProperties.put("username", username);
dbcpProperties.put("password", password);
// Isolation level
String isolationLevel = props.getProperty(Environment.ISOLATION);
if ((isolationLevel != null)
&& (isolationLevel.trim().length() > 0)) {
dbcpProperties.put("defaultTransactionIsolation",
isolationLevel);
}
// Turn off autocommit (unless autocommit property is set)
String autocommit = props.getProperty(AUTOCOMMIT);
if ((autocommit != null) && (autocommit.trim().length() > 0)) {
dbcpProperties.put("defaultAutoCommit", autocommit);
} else {
dbcpProperties.put("defaultAutoCommit",
String.valueOf(Boolean.FALSE));
}
// Pool size
String poolSize = props.getProperty(Environment.POOL_SIZE);
if ((poolSize != null) && (poolSize.trim().length() > 0)
&& (Integer.parseInt(poolSize) > 0)) {
dbcpProperties.put("maxActive", poolSize);
}
// Copy all "driver" properties into "connectionProperties"
Properties driverProps = ConnectionProviderFactory
.getConnectionProperties(props);
if (driverProps.size() > 0) {
StringBuffer connectionProperties = new StringBuffer();
for (Iterator iter = driverProps.entrySet().iterator(); iter
.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
connectionProperties.append(key).append('=').append(value);
if (iter.hasNext()) {
connectionProperties.append(';');
}
}
dbcpProperties.put("connectionProperties",
connectionProperties.toString());
}
// Copy all DBCP properties removing the prefix
for (Iterator iter = props.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
String key = (String) entry.getKey();
if (key.startsWith(PREFIX)) {
String property = key.substring(PREFIX.length());
String value = (String) entry.getValue();
dbcpProperties.put(property, value);
}
}
// Backward-compatibility
if (props.getProperty(DBCP_PS_MAXACTIVE) != null) {
dbcpProperties.put("poolPreparedStatements",
String.valueOf(Boolean.TRUE));
dbcpProperties.put("maxOpenPreparedStatements",
props.getProperty(DBCP_PS_MAXACTIVE));
}
// Some debug info
if (log.isDebugEnabled()) {
StringWriter sw = new StringWriter();
dbcpProperties.list(new PrintWriter(sw, true));
log.debug(sw.toString());
}
// Let the factory create the pool
ds = (BasicDataSource) BasicDataSourceFactory
.createDataSource(dbcpProperties);
// The BasicDataSource has lazy initialization
// borrowing a connection will start the DataSource
// and make sure it is configured correctly.
Connection conn = ds.getConnection();
conn.close();
// Log pool statistics before continuing.
logStatistics();
} catch (Exception e) {
String message = "Could not create a DBCP pool";
log.error(message, e);
if (ds != null) {
try {
ds.close();
} catch (Exception e2) {
// ignore
}
ds = null;
}
throw new HibernateException(message, e);
}
log.debug("Configure DBCPConnectionProvider complete");
}
public Connection getConnection() throws SQLException {
Connection conn = null;
try {
conn = ds.getConnection();
} finally {
logStatistics();
}
return conn;
}
public void closeConnection(Connection conn) throws SQLException {
try {
conn.close();
} finally {
logStatistics();
}
}
public void close() throws HibernateException {
log.debug("Close DBCPConnectionProvider");
logStatistics();
try {
if (ds != null) {
ds.close();
ds = null;
} else {
log.warn("Cannot close DBCP pool (not initialized)");
}
} catch (Exception e) {
throw new HibernateException("Could not close DBCP pool", e);
}
log.debug("Close DBCPConnectionProvider complete");
}
protected void logStatistics() {
if (log.isInfoEnabled()) {
log.info("active: " + ds.getNumActive() + " (max: "
+ ds.getMaxActive() + ") " + "idle: " + ds.getNumIdle()
+ "(max: " + ds.getMaxIdle() + ")");
}
}
public boolean supportsAggressiveRelease() {
return false;
}
}
3.在 hibernate.cfg.xml 中配置 DBCP
现在,链接您的“ DBCPConnectionProvider ”并在“ hibernate.cfg.xml ”中定义 DBCP 属性,例如:
文件:hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:MKYONG</property>
<property name="hibernate.connection.username">mkyong</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="hibernate.default_schema">MKYONG</property>
<property name="show_sql">true</property>
<property name="hibernate.connection.provider_class">
com.mkyong.util.DBCPConnectionProvider
</property>
<property name="hibernate.dbcp.initialSize">8</property>
<property name="hibernate.dbcp.maxActive">20</property>
<property name="hibernate.dbcp.maxIdle">20</property>
<property name="hibernate.dbcp.minIdle">0</property>
<mapping class="com.mkyong.user.DBUser"></mapping>
</session-factory>
</hibernate-configuration>
Note
The DBCP properties are supported in Hibernate via “hibernate.dbcp.properties-name“.
对于所有 DBCP 属性,请参考此 DBCP 配置页面。
4.运行它,输出
完成后,运行它并查看以下输出:
在应用程序启动阶段,连接池中创建了 8 个数据库连接,供您的 web 应用程序使用。
Download it – Hibernate-DBCP-Connection-Pool-Example.zip (10KB)
参考
- http://wiki.apache.org/commons/DBCP/Hibernate
- https://forum.hibernate.org/viewtopic.php?f=1&t = 947528&查看=下一张
- http://commons.apache.org/dbcp/configuration.html
- http://wiki.apache.org/commons/DBCP
如何在 Struts 2 中配置全局资源包
通常,您可能需要一个全局资源包(属性文件)来存储应用程序中所有类都可以使用的消息。
Download It – Struts2-global-resource-bundle-Example.zip
在 Struts 2 中,有三种方式来配置全局资源包:
1.struts.properties
在“struts.properties”文件中配置全局资源包,这里定义了一个名为“ global.properties 的属性文件作为全局资源包。
struts.custom.i18n.resources = global
对于多个资源包,只需用逗号分隔属性文件。
struts.custom.i18n.resources = global, another-properties-file
2.struts.xml
或者,您可以在 struts.xml 配置文件中将全局资源包配置为一个常量值。
<struts>
<constant name="struts.custom.i18n.resources" value="global" />
</struts>
3.听众
最后一种方法是使用 servlet 监听器加载一个属性文件作为全局资源包。
package com.mkyong.common.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.opensymphony.xwork2.util.LocalizedTextUtil;
public class GlobalMessagesListener implements ServletContextListener {
private static final String DEFAULT_RESOURCE = "global";
public void contextInitialized(ServletContextEvent arg0) {
LocalizedTextUtil.addDefaultResourceBundle(DEFAULT_RESOURCE);
}
public void contextDestroyed(ServletContextEvent arg0) {
}
}
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Struts 2 Web Application</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>
com.mkyong.common.listener.GlobalMessagesListener
</listener-class>
</listener>
</web-app>
如何在 Hibernate 中配置日志记录–SLF4j+Log4j
Try logback
Try logback logging framework, read this article for the “reasons to prefer logback over log4j. To integrate logback with Hibernate, refer this – How to configure logging in Hibernate – Logback
Hibernate 使用简单日志 Facade for Java (SLF4J) 将日志输出重定向到您的首选日志框架 is (log4j,JCL,JDK 日志,lofback…)。在本教程中,我们将向您展示如何使用 SLF4j + Log4j 日志框架在 Hibernate 中进行日志记录。
本文中使用的技术:
- Hibernate 3.6.3 .最终版
- slf4j-api-1.6.1
- slf4j-log4j12-1.6.1
- Eclipse 3.6
- Maven 3.0.3
1.获取 SLF4j + Log4j
要在 Hibernate 中进行日志记录,您需要“ slf4j-api.jar ”和您的首选绑定,如 log4j“slf4j-log4j 12 . jar”。只需在您的pom.xml
中声明依赖关系。
文件:pom.xml
<project ...>
<repositories>
<repository>
<id>JBoss repository</id>
<url>http://repository.jboss.org/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.3.Final</version>
</dependency>
<!-- slf4j-log4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>
</dependencies>
</project>
Where is slf4j-api.jar?
The slf4j-api.jar is defined as the dependency of “hibernate-core“, so , you do not need to declare it again.
2.Log4j 属性文件
创建一个" log4j.properties "文件,并将其放入项目的类路径中,见下图:
文件:log4.properties
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\mkyongapp.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{
ABSOLUTE} %5p %c{
1}:%L - %m%n
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{
ABSOLUTE} %5p %c{
1}:%L - %m%n
# Root logger option
log4j.rootLogger=INFO, file, stdout
# Log everything. Good for troubleshooting
log4j.logger.org.hibernate=INFO
# Log all JDBC parameters
log4j.logger.org.hibernate.type=ALL
使用这个 log4j 配置,它会将所有日志记录输出重定向到控制台和一个位于“C:\\mkyongapp.log
”的文件。
Note
Hibernate provides many settings to let developer to decide what to log. Always refer to this Hibernate Log Categories, choose some and implement it in your log file.
3.输出
试着运行你的 Hibernate web 应用程序,所有的日志输出将被记录在"C:\\mkyongapp.log
"文件中。见下图:
Download it – Log4j-Hibernate-Example.zip (7KB)
参考
- 【Java 的简单日志门面(SLF4J)
- http://logging.apache.org/log4j/1.2/
如何在 Hibernate–log back 中配置日志记录
在本教程中,我们将展示如何将日志记录框架与 Hibernate 集成。
本教程中使用的工具和技术:
- Hibernate 3.6.3 .最终版
- slf4j-api-1.6.1
- 回溯-核心-0.9.28
- 回溯-经典-0.9.28
- Eclipse 3.6
- Maven 3.0.3
1.获取 SLF4j + Logback
要在 Hibernate web 应用程序中使用 logback,您需要 3 个库:
- slf4j-api.jar
- 测井岩心
- 回溯-经典
文件:pom.xml
<project ...>
<repositories>
<repository>
<id>JBoss repository</id>
<url>http://repository.jboss.org/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.3.Final</version>
</dependency>
<!-- logback -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>0.9.28</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>0.9.28</version>
</dependency>
</dependencies>
</project>
Where is slf4j-api.jar?
The slf4j-api.jar is defined as the dependency of “hibernate-core“, so , you do not need to declare it again.
2.logback.xml
创建一个" logback.xml "文件,并将其放入项目的类路径中,见下图:
一个经典的“logback.xml
”例子。
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>%d{
yyyy-MM-dd_HH:mm:ss.SSS} %-5level %logger{
36} - %msg%n
</Pattern>
</encoder>
</appender>
<appender name="FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>c:/mkyongapp.log</file>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>%d{
yyyy-MM-dd_HH:mm:ss.SSS} [%thread] %-5level %logger{
36} - %msg%n
</Pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<FileNamePattern>c:/mkyongapp.%i.log.zip</FileNamePattern>
<MinIndex>1</MinIndex>
<MaxIndex>10</MaxIndex>
</rollingPolicy>
<triggeringPolicy
class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>2MB</MaxFileSize>
</triggeringPolicy>
</appender>
<logger name="org.hibernate.type" level="ALL" />
<logger name="org.hibernate" level="DEBUG" />
<root level="INFO">
<appender-ref ref="FILE" />
<appender-ref ref="STDOUT" />
</root>
</configuration>
使用这个logback.xml
配置,这意味着将所有 web 应用程序日志记录输出重定向到控制台和一个位于c:/mkyongapp.log
的文件。
3.输出
参见下面“C:\\mkyongapp.log
”处的日志记录输出:
//...
2011-04-23_14:34:08.055 [main] DEBUG o.h.transaction.JDBCTransaction - commit
2011-04-23_14:34:08.056 [main] DEBUG o.h.e.d.AbstractFlushingEventListener - processing flush-time cascades
2011-04-23_14:34:08.056 [main] DEBUG o.h.e.d.AbstractFlushingEventListener - dirty checking collections
2011-04-23_14:34:08.058 [main] DEBUG o.h.e.d.AbstractFlushingEventListener - Flushed: 1 insertions, 0 updates, 0 deletions to 1 objects
2011-04-23_14:34:08.058 [main] DEBUG o.h.e.d.AbstractFlushingEventListener - Flushed: 0 (re)creations, 0 updates, 0 removals to 0 collections
2011-04-23_14:34:08.059 [main] DEBUG org.hibernate.pretty.Printer - listing entities:
2011-04-23_14:34:08.060 [main] DEBUG org.hibernate.pretty.Printer - com.mkyong.user.DBUser{
username=Hibernate101, createdBy=system, userId=100, createdDate=Sat Apr 23 14:34:08 SGT 2011}
2011-04-23_14:34:08.064 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
2011-04-23_14:34:08.066 [main] DEBUG org.hibernate.SQL - insert into MKYONG.DBUSER (CREATED_BY, CREATED_DATE, USERNAME, USER_ID) values (?, ?, ?, ?)
2011-04-23_14:34:08.150 [main] TRACE o.h.type.descriptor.sql.BasicBinder - binding parameter [1] as [VARCHAR] - system
2011-04-23_14:34:08.152 [main] TRACE o.h.type.descriptor.sql.BasicBinder - binding parameter [2] as [DATE] - Sat Apr 23 14:34:08 SGT 2011
2011-04-23_14:34:08.153 [main] TRACE o.h.type.descriptor.sql.BasicBinder - binding parameter [3] as [VARCHAR] - Hibernate101
2011-04-23_14:34:08.153 [main] TRACE o.h.type.descriptor.sql.BasicBinder - binding parameter [4] as [INTEGER] - 100
Download it – Logback-Hibernate-Example.zip (8KB)
参考
- 【Java 的简单日志门面(SLF4J)
- 回退日志框架
如何在 Hibernate 中配置 C3P0 连接池
Connection Pool
Connection pool is good for performance, as it prevents Java application create a connection each time when interact with database and minimizes the cost of opening and closing connections.
参见 wiki 连接池的解释
Hibernate 自带内部连接池,但不适合生产使用。在本教程中,我们将向您展示如何将第三方连接池 C3P0 与 Hibernate 集成。
1.获取 hibernate-c3p0.jar
要集成 c3p0 和 Hibernate,需要 hibernate-c3p0.jar ,从 JBoss repository 获取。
文件:pom.xml
<project ...>
<repositories>
<repository>
<id>JBoss repository</id>
<url>http://repository.jboss.org/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.3.Final</version>
</dependency>
<!-- Hibernate c3p0 connection pool -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>3.6.3.Final</version>
</dependency>
</dependencies>
</project>
2.配置 c3p0 属性
为了配置 c3p0,将 c3p0 配置详细信息放入" hibernate.cfg.xml "中,如下所示:
文件:hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:MKYONG</property>
<property name="hibernate.connection.username">mkyong</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="hibernate.default_schema">MKYONG</property>
<property name="show_sql">true</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<mapping class="com.mkyong.user.DBUser"></mapping>
</session-factory>
</hibernate-configuration>
- hibernate . c3p 0 . min _ size–池中 JDBC 连接的最小数量。休眠默认值:1
- hibernate . c3p 0 . max _ size–池中 JDBC 连接的最大数量。休眠默认值:100
- hibernate . c3p 0 . time out–从池中删除空闲连接的时间(秒)。休眠默认值:0,永不过期。
- hibernate . c3p 0 . max _ statements–将缓存准备好的语句数。提高性能。休眠默认值:0,禁用缓存。
- hibernate . c3p 0 . idle _ test _ period–自动验证连接之前的空闲时间(秒)。休眠默认值:0
Note
For detail about hibernate-c3p0 configuration settings, please read this article.
运行它,输出
完成后,运行它并查看以下输出:
在连接初始化过程中,连接池中创建了 5 个数据库连接,以备 web 应用程序重用。
Download it – Hibernate-C3P0-Connection-Pool-Example.zip (8KB)
参考
- http://docs . JBoss . org/hibernate/core/3.6/reference/en-US/html _ single/# d0e 1748
- http://www.mchange.com/projects/c3p0/index.html#appendix_d
Tags : c3p0 connection pool hibernate
用 JDBC 驱动程序连接到 MySQL
一个 JDBC 的例子,展示了如何用 JDBC 驱动程序连接到 MySQL 数据库。
测试者:
- Java 8
- MySQL 5.7
- MySQL JDBC 驱动
mysql-connector-java:8.0.16
1.下载 MySQL JDBC 驱动程序
访问 https://dev.mysql.com/downloads/connector/j/下载最新的 MySQL JDBC 驱动程序。
2.JDBC 连接
2.1 建立到 MySQL 数据库的连接。
JDBCExample.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCExample {
public static void main(String[] args) {
// https://docs.oracle.com/javase/8/docs/api/java/sql/package-summary.html#package.description
// auto java.sql.Driver discovery -- no longer need to load a java.sql.Driver class via Class.forName
// register JDBC driver, optional since java 1.6
/*try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}*/
// auto close connection
try (Connection conn = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/test", "root", "password")) {
if (conn != null) {
System.out.println("Connected to the database!");
} else {
System.out.println("Failed to make connection!");
}
} catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
测试:
# compile
> javac JDBCExample.java
# run
> java JDBCExample
SQL State: 08001
No suitable driver found for jdbc:mysql://127.0.0.1:3306/test
要用java
命令运行它,我们需要手动加载 MySQL JDBC 驱动程序。假设所有东西都存储在c:\test
文件夹中,用这个-cp
选项再次运行它。
> java -cp "c:\test\mysql-connector-java-8.0.16.jar;c:\test" JDBCExample
Connected to the database!
3.Maven 项目
3.1 MySQL JDBC 驱动程序可以在 Maven 中央存储库中获得。
pom.xml
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
3.2 一个简单的 JDBC 选择示例。
JDBCExample2.java
import com.mkyong.jdbc.model.Employee;
import java.math.BigDecimal;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class JDBCExample2 {
public static void main(String[] args) {
System.out.println("MySQL JDBC Connection Testing ~");
List<Employee> result = new ArrayList<>();
String SQL_SELECT = "Select * from EMPLOYEE";
try (Connection conn = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/test", "root", "password");
PreparedStatement preparedStatement = conn.prepareStatement(SQL_SELECT)) {
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
long id = resultSet.getLong("ID");
String name = resultSet.getString("NAME");
BigDecimal salary = resultSet.getBigDecimal("SALARY");
Timestamp createdDate = resultSet.getTimestamp("CREATED_DATE");
Employee obj = new Employee();
obj.setId(id);
obj.setName(name);
obj.setSalary(salary);
// Timestamp -> LocalDateTime
obj.setCreatedDate(createdDate.toLocalDateTime());
result.add(obj);
}
result.forEach(x -> System.out.println(x));
} catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Employee.java
import java.math.BigDecimal;
import java.time.LocalDateTime;
public class Employee {
private Long id;
private String name;
private BigDecimal salary;
private LocalDateTime createdDate;
//...
}
表定义。
CREATE TABLE EMPLOYEE
(
ID INT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(100) NOT NULL,
SALARY DECIMAL(15, 2) NOT NULL,
CREATED_DATE DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (ID)
);
下载源代码
$ git clone https://github.com/mkyong/java-jdbc.git
参考
Java–如何将 byte[]保存到文件中
本文展示了几种将byte[]
保存到文件中的方法。
对于 JDK 1.7 和更高版本,NIO Files.write 是将byte[]
保存到文件的最简单的解决方案。
// bytes = byte[]
Path path = Paths.get("/path/file");
Files.write(path, bytes);
FileOutputStream
是最好的选择。
try (FileOutputStream fos = new FileOutputStream("/path/file")) {
fos.write(bytes);
//fos.close // no need, try-with-resources auto close
}
如果我们有 Apache Commons IO ,试试FileUtils
。
FileUtils.writeByteArrayToFile(new File("/path/file"), bytes);
pom.xml
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
</dependency>
1.将字节[]保存到文件。
下面的例子读取一个文件并将数据转换成一个byte[]
。稍后,我们将byte[]
保存到另一个文件中。
ByteToFile.java
package com.mkyong.io.howto;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ByteToFile {
public static void main(String[] args) {
try {
// tested with character data and binary data
// file to bytes[]
byte[] bytes = Files.readAllBytes(Paths.get("/home/mkyong/test/file.txt"));
// save byte[] to a file
writeBytesToFile("/home/mkyong/test/file2.txt", bytes);
writeBytesToFileNio("/home/mkyong/test/file3.txt", bytes);
writeBytesToFileApache("/home/mkyong/test/file4.txt", bytes);
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
//JDK 7 - FileOutputStream + try-with-resources
private static void writeBytesToFile(String fileOutput, byte[] bytes)
throws IOException {
try (FileOutputStream fos = new FileOutputStream(fileOutput)) {
fos.write(bytes);
}
}
//JDK 7, NIO, Files.write
private static void writeBytesToFileNio(String fileOutput, byte[] bytes)
throws IOException {
Path path = Paths.get(fileOutput);
Files.write(path, bytes);
}
// Apache Commons IO
private static void writeBytesToFileApache(String fileOutput, byte[] bytes)
throws IOException {
FileUtils.writeByteArrayToFile(new File(fileOutput), bytes);
}
}
下载源代码
$ git 克隆https://github.com/mkyong/core-java
$ cd java-io
参考
- Apache Commons FileUtils JavaDoc
- Apache common me
- FileOutputStream JavaDoc
- 文件 JavaDoc
- Java–如何将文件转换成字节数组
如何在 BeanWrapperFieldSetMapper 中转换日期
读取下面的 Spring 批处理作业,它从" domain.csv "中读取数据,并将其映射到一个域对象。
job-example.xml
<bean class="org.springframework.batch.item.file.FlatFileItemReader" >
<property name="resource" value="file:outputs/csv/domain.csv" />
<property name="lineMapper">
<bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<property name="lineTokenizer">
<bean
class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
<property name="names" value="id, domainName, lastModifiedDate" />
</bean>
</property>
<property name="fieldSetMapper">
<bean
class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper">
<property name="prototypeBeanName" value="domain" />
</bean>
</property>
</bean>
</property>
</bean>
<bean id="domain" class="com.mkyong.batch.Domain" scope="prototype" />
domain.csv
1,facebook.com,Mon Jul 15 16:32:21 MYT 2013
2,google.com,Mon Jul 15 16:32:21 MYT 2013
3,youtube.com,Mon Jul 15 16:32:21 MYT 2013
4,yahoo.com,Mon Jul 15 16:32:21 MYT 2013
5,amazon.com,Mon Jul 15 16:32:21 MYT 2013
Domain.java
import java.util.Date;
public class DomainRanking {
private int id;
private String domainName;
private Date lastModifiedDate;
//...
}
问题
问题是如何将字符串日期Mon Jul 15 16:32:21 MYT 2013
映射/转换为java.util.Date
?运行上述作业将提示以下错误消息:
Cannot convert value of type [java.lang.String] to required type [java.util.Date]
for property 'lastModifiedDate':
no matching editors or conversion strategy found
解决办法
参考BeanWrapperFieldSetMapper JavaDoc:
要定制将字段集值转换为注入原型所需类型的方式,有几种选择。您可以通过 customEditors 属性直接注入 PropertyEditor 实例…
为了修复它,声明一个CustomDateEditor
并通过customEditors
属性注入到BeanWrapperFieldSetMapper
中。
job-example.xml
<bean id="dateEditor"
class="org.springframework.beans.propertyeditors.CustomDateEditor">
<constructor-arg>
<bean class="java.text.SimpleDateFormat">
<constructor-arg value="EEE MMM dd HH:mm:ss z yyyy" />
</bean>
</constructor-arg>
<constructor-arg value="true" />
</bean>
<bean class="org.springframework.batch.item.file.FlatFileItemReader" >
<property name="resource" value="file:outputs/csv/domain.csv" />
<property name="lineMapper">
<bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<property name="lineTokenizer">
<bean
class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
<property name="names" value="id, domainName, lastModifiedDate" />
</bean>
</property>
<property name="fieldSetMapper">
<bean
class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper">
<property name="prototypeBeanName" value="domain" />
<property name="customEditors">
<map>
<entry key="java.util.Date">
<ref local="dateEditor" />
</entry>
</map>
</property>
</bean>
</property>
</bean>
</property>
</bean>
<bean id="domain" class="com.mkyong.batch.Domain" scope="prototype" />
字符串日期“MYT 2013 年 7 月 15 日星期一 16:32:21”由“EEE MMM dd HH:mm:ss z yyyy”表示。
Note
Do not injects the CustomDateEditor
via CustomEditorConfigurer
(globally), it will not works.
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date">
<ref local="dateEditor" />
</entry>
</map>
</property>
</bean>
参考
- BeanWrapperFieldSetMapper JavaDoc
- BeanWrapperFieldSetMapper 不适用于日期
- java.text.SimpleDateFormat JavaDoc
- Spring Batch–如何将字符串从文件转换为日期
- Spring 将日期注入 Bean 属性-custom Date editor
- 如何将字符串转换为日期–Java
Java–如何将文件转换成字节[]
在 Java 中,我们可以使用Files.readAllBytes(path)
将一个File
对象转换成一个byte[]
。
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
String filePath = "/path/to/file";
// file to byte[], Path
byte[] bytes = Files.readAllBytes(Paths.get(filePath));
// file to byte[], File -> Path
File file = new File(filePath);
byte[] bytes = Files.readAllBytes(file.toPath());
NIO Files
类从 Java 7 开始就可用了。
1.文件输入流
在 Java 7 之前,我们可以初始化一个预定义大小的新byte[]
(与文件长度相同),使用FileInputStream
将文件数据读入新的byte[]
。
// file to byte[], old and classic way, before Java 7
private static void readFileToBytes(String filePath) throws IOException {
File file = new File(filePath);
byte[] bytes = new byte[(int) file.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
//read file into bytes[]
fis.read(bytes);
} finally {
if (fis != null) {
fis.close();
}
}
}
还是这个try-with-resources
版本。
private static void readFileToBytes(String filePath) throws IOException {
File file = new File(filePath);
byte[] bytes = new byte[(int) file.length()];
// funny, if can use Java 7, please uses Files.readAllBytes(path)
try(FileInputStream fis = new FileInputStream(file)){
fis.read(bytes);
}
}
2.Apache commons-Apache 公用程式
如果我们有 Apache Commons IO ,试试FileUtils
。
import org.apache.commons.io.FileUtils;
//...
File file = new File("/path/file");
byte[] bytes = FileUtils.readFileToByteArray(file);
pom.xml
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
</dependency>
3.将文件转换为 byte[],反之亦然。
下面的例子使用 NIO Files.readAllBytes
将一个图像文件读入一个byte[]
,并使用Files.write
将byte[]
保存到一个新的图像文件中。
FileToBytes.java
package com.mkyong.io.howto;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileToBytes {
public static void main(String[] args) {
try {
String filePath = "/home/mkyong/test/phone.png";
// file to bytes[]
byte[] bytes = Files.readAllBytes(Paths.get(filePath));
// bytes[] to file
Path path = Paths.get("/home/mkyong/test/phone2.png");
Files.write(path, bytes);
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
下载源代码
$ git 克隆https://github.com/mkyong/core-java
$ cd java-io
参考
- 文件输入流 JavaDoc
- 文件 JavaDoc
- Apache common me
- Java–如何将字节数组保存到文件中
Java–将文件转换为十六进制
这篇文章展示了如何将一个文件转换成一个十六进制(hex) 的代表格式。
例如,下面是一个文本文件。
/path/to/text.txt
ABCDEFG
12345678
!@#$%^&*()
Testing only
我们将把上面的文件转换成下面的十六进制格式。
41 42 43 44 45 46 47 0D 0A 31 32 33 34 35 36 | ABCDEFG..123456
37 38 0D 0A 21 40 23 24 25 5E 26 2A 28 29 0D | 78..!@#$%^&*().
0A 54 65 73 74 69 6E 67 20 6F 6E 6C 79 | .Testing only
1.Java 将文件转换为十六进制
想法是将文件读入一个InputStream
,并使用 String.format(%X) 将每个字节转换成一个十六进制代码。
FileToHex.java
package com.mkyong.io.howto;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileToHex {
private static final String NEW_LINE = System.lineSeparator();
private static final String UNKNOWN_CHARACTER = ".";
public static void main(String[] args) throws IOException {
String file = "/path/to/text.txt";
String s = convertFileToHex(Paths.get(file));
System.out.println(s);
}
public static String convertFileToHex(Path path) throws IOException {
if (Files.notExists(path)) {
throw new IllegalArgumentException("File not found! " + path);
}
StringBuilder result = new StringBuilder();
StringBuilder hex = new StringBuilder();
StringBuilder input = new StringBuilder();
int count = 0;
int value;
// path to inputstream....
try (InputStream inputStream = Files.newInputStream(path)) {
while ((value = inputStream.read()) != -1) {
hex.append(String.format("%02X ", value));
//If the character is unable to convert, just prints a dot "."
if (!Character.isISOControl(value)) {
input.append((char) value);
} else {
input.append(UNKNOWN_CHARACTER);
}
// After 15 bytes, reset everything for formatting purpose
if (count == 14) {
result.append(String.format("%-60s | %s%n", hex, input));
hex.setLength(0);
input.setLength(0);
count = 0;
} else {
count++;
}
}
// if the count>0, meaning there is remaining content
if (count > 0) {
result.append(String.format("%-60s | %s%n", hex, input));
}
}
return result.toString();
}
}
2.将图像文件转换为十六进制
使用图像文件运行上述程序。
String file = "/path/to/hello.png";
输出
89 50 4E 47 0D 0A 1A 0A 00 00 00 0D 49 48 44 | .PNG........IHD
52 00 00 03 11 00 00 01 1E 08 06 00 00 00 F5 | R.............õ
AE 98 9A 00 00 00 09 70 48 59 73 00 00 12 74 | ®......pHYs...t
00 00 12 74 01 DE 66 1F 78 00 00 00 07 74 49 | ...t.Þf.x....tI
//...
20 08 42 4B 88 13 21 08 82 20 08 82 20 08 42 | .BK..!.. .. .B
4B FC 7F 0B 00 ED 81 F6 3A 58 EC 00 00 00 00 | Kü...í.ö:Xì....
49 45 4E 44 AE 42 60 82 | IEND®B`.
下载源代码
$ git 克隆https://github.com/mkyong/core-java
$ cd java-io/howto
参考
如何在 Java 中将 InputStream 转换成文件
下面是一些将InputStream
转换成File
的 Java 例子。
- 普通 Java–文件输出流
- Apache common io–file utils . copyinputstreamtofile
- Java 7–files . copy
- Java 9–input stream . transfer
1。普通 Java–文件输出流
这个例子下载了google.com
HTML 页面,并将其作为InputStream
返回。我们用FileOutputStream
把InputStream
复制成File
,保存在某个地方。
InputStreamToFile1.java
package com.mkyong.io.howto;
import java.io.*;
import java.net.URI;
public class InputStreamToFile1 {
/**
* The default buffer size
*/
public static final int DEFAULT_BUFFER_SIZE = 8192;
public static void main(String[] args) throws IOException {
URI u = URI.create("https://www.google.com/");
try (InputStream inputStream = u.toURL().openStream()) {
File file = new File("c:\\test\\google.txt");
copyInputStreamToFile(inputStream, file);
}
}
private static void copyInputStreamToFile(InputStream inputStream, File file)
throws IOException {
// append = false
try (FileOutputStream outputStream = new FileOutputStream(file, false)) {
int read;
byte[] bytes = new byte[DEFAULT_BUFFER_SIZE];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
}
}
}
2 .Apache common me〔t1〕
如果项目中有 Apache Commons IO,我们可以使用FileUtils.copyInputStreamToFile
将InputStream
复制到File
中。
pom.xml
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
</dependency>
InputStreamToFile2.java
package com.mkyong.io.howto;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
public class InputStreamToFile2 {
public static void main(String[] args) throws IOException {
URI u = URI.create("https://www.google.com/");
try (InputStream inputStream = u.toURL().openStream()) {
File file = new File("c:\\test\\google.txt");
// commons-io
FileUtils.copyInputStreamToFile(inputStream, file);
}
}
}
3。Java 1.7–files . copy
在 Java 1.7 中,我们可以使用Files.copy
将InputStream
复制到一个Path
。
InputStreamToFile3.java
URI u = URI.create("https://www.google.com/");
try (InputStream inputStream = u.toURL().openStream()) {
File file = new File("c:\\test\\google.txt");
// Java 1.7
Files.copy(inputStream, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
4 .Java 9–input stream . transfer
在 Java 9 中,我们可以使用新的 InputStream#transferTo 将InputStream
直接复制到OutputStream
中。
InputStreamToFile4.java
package com.mkyong.io.howto;
import java.io.*;
import java.net.URI;
public class InputStreamToFile4 {
public static void main(String[] args) throws IOException {
URI u = URI.create("https://www.google.com/");
try (InputStream inputStream = u.toURL().openStream()) {
File file = new File("c:\\test\\google.txt");
// Java 9
copyInputStreamToFileJava9(inputStream, file);
}
}
// Java 9
private static void copyInputStreamToFileJava9(InputStream input, File file)
throws IOException {
// append = false
try (OutputStream output = new FileOutputStream(file, false)) {
input.transferTo(output);
}
}
}
5。将文件转换为输入流
我们可以使用FileInputStream
将一个File
转换成一个InputStream
。
File file = new File("d:\\download\\google.txt");
InputStream inputStream = new FileInputStream(file);
下载源代码
$ git 克隆https://github.com/mkyong/core-java
$ CD Java-io/操作方法
参考文献
- FileOutputStream JavaDoc
- InputStream JavaDoc
- 如何在 Java 中复制文件
- Apache common me
- 在 Java 中把 InputStream 转换成 String
- 在 Java 中将 InputStream 转换为 buffered reader
Jackson——将 JSON 字符串转换成映射
在 Jackson 中,我们可以使用mapper.readValue(json, Map.class)
将 JSON 字符串转换成Map
用杰克逊 2.9.8 测试的 PS
pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
1.要映射的 JSON 字符串
JacksonMapExample1.java
package com.mkyong;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Map;
public class JacksonMapExample1 {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
String json = "{\"name\":\"mkyong\", \"age\":\"37\"}";
try {
// convert JSON string to Map
Map<String, String> map = mapper.readValue(json, Map.class);
// it works
//Map<String, String> map = mapper.readValue(json, new TypeReference<Map<String, String>>() {});
System.out.println(map);
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出
{
name=mkyong, age=37}
2.映射到 JSON 字符串
JacksonMapExample2.java
package com.mkyong;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
public class JacksonMapExample2 {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
Map<String, String> map = new HashMap<>();
map.put("name", "mkyong");
map.put("age", "37");
try {
// convert map to JSON string
String json = mapper.writeValueAsString(map);
System.out.println(json); // compact-print
json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map);
System.out.println(json); // pretty-print
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
输出
{
"name":"mkyong","age":"37"}
{
"name" : "mkyong",
"age" : "37"
}
3.要映射的 JSON 数组?
3.1 JSON 数组字符串是这样的
[{
"age":29,"name":"mkyong"}, {
"age":30,"name":"fong"}]
它应该转换成一个List
,而不是一个Map
,例如:
// convert JSON array to List
List<Person> list = Arrays.asList(mapper.readValue(json, Person[].class));
Note
Read this Jackson – Convert JSON array string to List
参考
如何在 Java 对象和 JSON 之间转换(Jackson)
在本教程中,我们将向您展示如何使用 Jackson 1.x 数据绑定在 Java 对象和 JSON 之间进行转换。
Note
Jackson 1.x is a maintenance project, please use Jackson 2.x instead.Note
This tutorial is obsolete, no more update, please refer to the latest Jackson 2 tutorial – Object to / from JSON.
1.快速参考
1.1 将 Java 对象转换成 JSON,writeValue(...)
ObjectMapper mapper = new ObjectMapper();
User user = new User();
//Object to JSON in file
mapper.writeValue(new File("c:\\user.json"), user);
//Object to JSON in String
String jsonInString = mapper.writeValueAsString(user);
1.2 将 JSON 转换成 Java 对象,readValue(...)
ObjectMapper mapper = new ObjectMapper();
String jsonInString = "{'name' : 'mkyong'}";
//JSON from file to Object
User user = mapper.readValue(new File("c:\\user.json"), User.class);
//JSON from String to Object
User user = mapper.readValue(jsonInString, User.class);
所有的例子都用杰克逊 1.9.13 进行了测试
2.杰克逊依赖
对于 Jackson 1.x,它包含 6 个不同用途的独立 jar,在大多数情况下,你只需要jackson-mapper-asl
。
pom.xml
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
3.POJO(普通旧 Java 对象)
用于测试的用户对象。
User.java
package com.mkyong.json;
import java.util.List;
public class User {
private String name;
private int age;
private List<String> messages;
//getters and setters
}
4.JSON 的 Java 对象
将一个user
对象转换成 JSON 格式的字符串。
JacksonExample.java
package com.mkyong.json;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class JacksonExample {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
//For testing
User user = createDummyUser();
try {
//Convert object to JSON string and save into file directly
mapper.writeValue(new File("D:\\user.json"), user);
//Convert object to JSON string
String jsonInString = mapper.writeValueAsString(user);
System.out.println(jsonInString);
//Convert object to JSON string and pretty print
jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);
System.out.println(jsonInString);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static User createDummyUser(){
User user = new User();
user.setName("mkyong");
user.setAge(33);
List<String> msg = new ArrayList<>();
msg.add("hello jackson 1");
msg.add("hello jackson 2");
msg.add("hello jackson 3");
user.setMessages(msg);
return user;
}
}
输出
//new json file is created in D:\\user.json"
{
"name":"mkyong","age":33,"messages":["hello jackson 1","hello jackson 2","hello jackson 3"]}
{
"name" : "mkyong",
"age" : 33,
"messages" : [ "hello jackson 1", "hello jackson 2", "hello jackson 3" ]
}
5.JSON 到 Java 对象
读取 JSON 字符串并将其转换回 Java 对象。
JacksonExample.java
package com.mkyong.json;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class JacksonExample {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
try {
// Convert JSON string from file to Object
User user = mapper.readValue(new File("G:\\user.json"), User.class);
System.out.println(user);
// Convert JSON string to Object
String jsonInString = "{\"age\":33,\"messages\":[\"msg 1\",\"msg 2\"],\"name\":\"mkyong\"}";
User user1 = mapper.readValue(jsonInString, User.class);
System.out.println(user1);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出
User [name=mkyong, age=33, messages=[hello jackson 1, hello jackson 2, hello jackson 3]]
User [name=mkyong, age=33, messages=[msg 1, msg 2]]
6.@JsonView
从 1.4 版本开始,Jackson 就支持这个功能,它可以让你控制显示哪些字段。
6.1 一个简单的类。
Views.java
package com.mkyong.json;
public class Views {
public static class NameOnly{
};
public static class AgeAndName extends NameOnly{
};
}
6.2 在您想要显示的字段上进行注释。
User.java
package com.mkyong.json;
import java.util.List;
import org.codehaus.jackson.map.annotate.JsonView;
public class User {
@JsonView(Views.NameOnly.class)
private String name;
@JsonView(Views.AgeAndName.class)
private int age;
private List<String> messages;
//getter and setters
}
6.3 通过writerWithView()
使能@JsonView
。
JacksonExample.java
package com.mkyong.json;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
public class JacksonExample {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
//By default all fields without explicit view definition are included, disable this
mapper.configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION, false);
//For testing
User user = createDummyUser();
try {
//display name only
String jsonInString = mapper.writerWithView(Views.NameOnly.class).writeValueAsString(user);
System.out.println(jsonInString);
//display namd ana age
jsonInString = mapper.writerWithView(Views.AgeAndName.class).writeValueAsString(user);
System.out.println(jsonInString);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static User createDummyUser(){
User user = new User();
user.setName("mkyong");
user.setAge(33);
List<String> msg = new ArrayList<>();
msg.add("hello jackson 1");
msg.add("hello jackson 2");
msg.add("hello jackson 3");
user.setMessages(msg);
return user;
}
}
输出
{
"name":"mkyong"}
{
"name":"mkyong","age":33}
参考
如何将字符串转换为日期–Java
在本教程中,我们将向您展示如何将字符串转换为java.util.Date
。许多 Java 初学者被日期转换所困扰,希望这篇总结指南能在某些方面帮助你。
// String -> Date
SimpleDateFormat.parse(String);
// Date -> String
SimpleDateFormat.format(date);
关于java.text.SimpleDateFormat
中使用的一些常见的日期和时间模式,请参考下表 JavaDoc
| 信 | 描述 | 例子 |
| y | 年 | Two thousand and thirteen |
| M | 一年中的月份 | 2007 年 7 月 |
| d | 一个月中的第几天 | 1-31 |
| E | 周中的日名称 | 星期五,星期天 |
| a | Am/pm 标记 | 上午,下午 |
| H | 一天中的小时 | 0-23 |
| h | 上午/下午的小时 | 1-12 |
| m | 小时中的分钟 | 0-60 |
| s | 分钟秒 | 0-60 |
Note
You may interest at this Java 8 example – How to convert String to LocalDate
1.string = 2013 年 6 月 7 日
如果是 3 'M ',则月份被解释为文本(周一至十二月),否则为数字(01-12)。
TestDateExample1.java
package com.mkyong.date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDateExample1 {
public static void main(String[] argv) {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String dateInString = "7-Jun-2013";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
输出
Fri Jun 07 00:00:00 MYT 2013
07-Jun-2013
2.string = 2013 年 7 月 6 日
TestDateExample2.java
package com.mkyong.date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDateExample2 {
public static void main(String[] argv) {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateInString = "07/06/2013";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
输出
Fri Jun 07 00:00:00 MYT 2013
07/06/2013
3.String = Fri,2013 年 6 月 7 日
TestDateExample3.java
package com.mkyong.date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDateExample3 {
public static void main(String[] argv) {
SimpleDateFormat formatter = new SimpleDateFormat("E, MMM dd yyyy");
String dateInString = "Fri, June 7 2013";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
输出
Fri Jun 07 00:00:00 MYT 2013
Fri, Jun 07 2013
4.String =年 6 月 7 日星期五下午 12 点 10 分 56 秒
TestDateExample4.java
package com.mkyong.date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDateExample4 {
public static void main(String[] argv) {
SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMM dd, yyyy HH:mm:ss a");
String dateInString = "Friday, Jun 7, 2013 12:10:56 PM";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
输出
Fri Jun 07 12:10:56 MYT 2013
Friday, Jun 07, 2013 12:10:56 PM
5.String = 2014-10-05T15:23:01Z
Z 后缀表示 UTC,java.util.SimpleDateFormat
解析不正确,需要用’+0000 '替换后缀 Z。
TestDateExample5.java
package com.mkyong.date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDateExample5 {
public static void main(String[] argv) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateInString = "2014-10-05T15:23:01Z";
try {
Date date = formatter.parse(dateInString.replaceAll("Z$", "+0000"));
System.out.println(date);
System.out.println("time zone : " + TimeZone.getDefault().getID());
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
输出
Sun Oct 05 23:23:01 MYT 2014
time zone : Asia/Kuala_Lumpur
2014-10-05T23:23:01+0800
在 Java 8 中,你可以把它转换成一个java.time.Instant
对象,用指定的时区显示。
TestDateExample6.java
package com.mkyong.date;
import java.time.*;
public class TestDateExample6 {
public static void main(String[] argv) {
String dateInString = "2014-10-05T15:23:01Z";
Instant instant = Instant.parse(dateInString);
System.out.println(instant);
//get date time only
LocalDateTime result = LocalDateTime.ofInstant(instant, ZoneId.of(ZoneOffset.UTC.getId()));
System.out.println(result);
//get date time + timezone
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("Africa/Tripoli"));
System.out.println(zonedDateTime);
//get date time + timezone
ZonedDateTime zonedDateTime2 = instant.atZone(ZoneId.of("Europe/Athens"));
System.out.println(zonedDateTime2);
}
}
输出
2014-10-05T15:23:01Z
2014-10-05T15:23:01
2014-10-05T17:23:01+02:00[Africa/Tripoli]
2014-10-05T18:23:01+03:00[Europe/Athens]
参考
- 简单日期格式 JavaDoc
- Java 8–如何将字符串转换为本地日期
- stack overflow:simple date format 用“Z”字面值解析日期
- 维基百科:ISO 8601
- 时区和时差等级
- 格林威治时间 VS 世界协调时
- 什么是时区?
- Joda 时间
如何在 Java 中将字符串转换成 InputStream
在 Java 中,我们可以使用ByteArrayInputStream
将一个String
转换成一个InputStream
。
String str = "mkyong.com";
InputStream is = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
目录
1. ByteArrayInputStream
这个例子使用ByteArrayInputStream
将一个String
转换成一个InputStream
,并保存到一个文件中。
StringToInputStream.java
package com.mkyong.string;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class ConvertStringToInputStream {
public static final int DEFAULT_BUFFER_SIZE = 8192;
public static void main(String[] args) throws IOException {
String name = "mkyong.com";
// String to InputStream
InputStream is = new ByteArrayInputStream(name.getBytes(StandardCharsets.UTF_8));
// save to a file
save(is, "c:\\test\\file.txt");
}
// save the InputStream to a File
private static void save(final InputStream is, final String fileName)
throws IOException {
// read bytes from InputStream and write it to FileOutputStream
try (FileOutputStream outputStream =
new FileOutputStream(new File(fileName), false)) {
int read;
byte[] bytes = new byte[DEFAULT_BUFFER_SIZE];
while ((read = is.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
}
}
}
2 .Apache common io–ioutils
这个例子使用commons-io
库、IOUtils.toInputStream
API 将String
转换为InputStream
。
pom.xml
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
import org.apache.commons.io.IOUtils;
// String to InputStream
InputStream result = IOUtils.toInputStream(str, StandardCharsets.UTF_8);
回顾一下IOUtils.toInputStream
的源代码,它是用同一个ByteArrayInputStream
把一个String
转换成一个InputStream
。
package org.apache.commons.io;
public class IOUtils {
public static InputStream toInputStream(final String input, final Charset charset) {
return new ByteArrayInputStream(input.getBytes(Charsets.toCharset(charset)));
}
//...
}
延伸阅读
Java 中把 InputStream 转换成 String
3。下载源代码
$ git 克隆https://github.com/mkyong/core-java
$ cd java-string
或者
$ cd java-io
4。参考文献
- ByteArrayOutputStream JavaDoc
- Apache common me
- 如何在 Java 中将 InputStream 转换成文件