Java从数据库读取信息执行文件拷贝,简单实用。
package read_db_copy_files;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class MysqlDemo {
public static void main(String[] args) throws Exception {
ArrayList<String> bd_list = readF1("bd.log");
Connection conn = null;
String sql;
String url = "jdbc:mysql://192.168.6.93:3306/resume_parse?"
+ "user=miaohr&password=123456&useUnicode=true&characterEncoding=UTF8";
// 目标文件夹
String dest_dir = "./dest_dir/";
// 创建目标文件夹
(new File(dest_dir)).mkdirs();
try {
Class.forName("com.mysql.jdbc.Driver");// 动态加载mysql驱动
System.out.println("成功加载MySQL驱动程序");
// 一个Connection代表一个数据库连接
conn = DriverManager.getConnection(url);
// Statement里面带有很多方法,比如executeUpdate可以实现插入,更新和删除等
Statement stmt = conn.createStatement();
System.out.println("filepath\tip");
for(String bd_string : bd_list){
sql = "SELECT filepath,ip,filename FROM `middleware_parse_count` WHERE filename='"+bd_string+"'";
ResultSet rs = stmt.executeQuery(sql);// executeQuery会返回结果的集合,否则返回空值
while (rs.next()) {
//string = "/mnt/smbfs94/resume_parse_manager/Files_slave_model_bak/fen/2015-05-22//13bceea1-aeb8-48af-9079-f10b1a886a80.doc";
//System.out.println(rs.getString(1) + "\t" + rs.getString(2));// 入如果返回的是int类型可以用getInt()
String newpath = rs.getString(1);
String[] strarray=rs.getString(2).split("\\.");
String destpath = dest_dir+rs.getString(3);
newpath = newpath.replaceFirst("/opt/", "/mnt/smbfs"+strarray[3]+"/");
System.out.println(newpath);
copyFile(new File(newpath),new File(destpath));
}
}
} catch (SQLException e) {
System.out.println("MySQL操作错误");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.close();
}
}
public static ArrayList<String> readF1(String filePath) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(filePath)));
ArrayList<String> list1 = new ArrayList<String>();
for (String line = br.readLine(); line != null; line = br.readLine()) {
System.out.println(line);
list1.add(line);
}
br.close();
return list1;
}
// 复制文件
public static void copyFile(File sourceFile, File targetFile) throws IOException {
BufferedInputStream inBuff = null;
BufferedOutputStream outBuff = null;
try {
// 新建文件输入流并对它进行缓冲
inBuff = new BufferedInputStream(new FileInputStream(sourceFile));
// 新建文件输出流并对它进行缓冲
outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));