通过common io包进行文件的读取和写入,先要导入common io jar包:
<!-- https://mvnrepository.com/artifact/commons-io/commons-io 数据的读写包-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
通过FileUtils工具类写入:
package com.amat.db;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.commons.io.FileUtils;
public class CsvFromDb {
public static void main(String[] args) {
// 导入mysql依赖包,通过class.forname方法获取到Driver这个对象(获取mysql驱动)
// 底层逻辑详解:https://www.jb51.net/article/117468.htm
String className = "com.mysql.jdbc.Driver";// mysql驱动
Connection connection = null;
/*
* 连接Oracle的驱动
*/
// String className2 = "oracle.jdbc.OracleDriver";
try {
String path = System.getProperty("user.dir");
System.out.println(path);
File file = new File(path + File.separator + "data" + File.separator + "test03.xlsx");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Class.forName(className);
String mysqlurl = "jdbc:mysql://127.0.0.1:3306/wftest01?characterEncoding=utf8&useSSL=false";
// String oracleurl = "jdbc:oracle:thin:@10.0.30.64:1521:orcl";
try {
connection = DriverManager.getConnection(mysqlurl, "root", "123456");
// 准备SQL
String sqlString = "select * from person";
// 创建执行SQL对象
Statement statement = connection.createStatement();
ResultSet set = statement.executeQuery(sqlString);
while (set.next()) {
String name = set.getString("PersonName");
String ageString = set.getString("personage");
String personsex = set.getString("PersonSex");
System.out.println(name + "今年" + ageString + "是个" + personsex + "性");
String lineString = name + "," + ageString + "," + personsex + "," + "\n";
try {
// FileUtils.write(file, lineString, false);// false的话会覆盖,只会将最新读取的数据写入
FileUtils.write(file, lineString, true);//true 的话会读一条写一条,不会覆盖。
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
File类常用方法: