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));
// 緩沖數組
byte[] b = new byte[1024 * 5];
int len;
while ((len = inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
// 刷新此緩沖的輸出流
outBuff.flush();
} finally {
// 關閉流
if (inBuff != null)
inBuff.close();
if (outBuff != null)
outBuff.close();
}
}
}