34,838
社区成员




import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class UpAndDown {
//数据库配置-------------------------------
private String jdbcDriver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
//private String jdbcDriver = "com.mysql.jdbc.Driver";
private String url = "localhost";
private String userName = "sa";
private String password = "12345";
//-----------------------------------------
private String DbUrl = "jdbc:microsoft:sqlserver://" + url + ":1433;DataBaseName=largeFile";
//private String DbUrl = "jdbc:mysql://" + url + ":3306/largeFile";
private Connection conn = null;
//文件上传到数据库,String filePath:文件名(包括路径)
public void uploadFile(String filePath) throws Exception {
PreparedStatement ps = null;
FileInputStream fis = null;
File uploadFile = new File(filePath);
if(!uploadFile.exists()) {
System.out.println("文件不存在");
return;
}
Class.forName(jdbcDriver);
conn = java.sql.DriverManager.getConnection(DbUrl, userName, password);
fis = new FileInputStream(uploadFile);
ps = conn.prepareStatement("INSERT INTO myFile (largeFile) VALUES (?)");
ps.setBinaryStream(1, fis, (int)uploadFile.length());
ps.executeUpdate();
fis.close();
ps.close();
conn.close();
System.out.println("文件上传成功");
}
//文件下载到本地,String path:下载目的地,带"\\"
public void downloadFile(String path) throws Exception {
PreparedStatement ps = null;
ResultSet rs = null;
File filePath = new File(path);
File downloadFile = null;
InputStream is = null;
FileOutputStream fos = null;
if(!filePath.exists()) filePath.mkdir();
Class.forName(jdbcDriver);
conn = java.sql.DriverManager.getConnection(DbUrl, userName, password);
ps = conn.prepareStatement("SELECT * FROM myFile", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = ps.executeQuery();
while(rs.next()) {
byte[] buffer = new byte[1024];
downloadFile = new File(path + rs.getString("id") + ".mpg");
if(!downloadFile.exists()) {
fos = new FileOutputStream(downloadFile);
is = rs.getBinaryStream("largeFile");
int count = 0;
while((count = is.read(buffer)) != -1) {
fos.write(buffer, 0, count);
}
} else System.out.println("文件:" + downloadFile.getName() + "已存在");
}
rs.close();
ps.close();
fos.close();
is.close();
conn.close();
System.out.println("文件下载成功");
}
//清空文件所在的数据库表,因为在企业管理器里手动删不了,需要用SQL语句删除
public void clearDB() throws Exception {
java.sql.PreparedStatement ps = null;
Class.forName(jdbcDriver);
conn=java.sql.DriverManager.getConnection(DbUrl, userName, password);
ps = conn.prepareStatement("DELETE FROM myFile");
ps.executeUpdate();
System.out.println("清空成功");
}
public static void main(String[] args) {
UpAndDown ud = new UpAndDown();
try {
ud.uploadFile("d:\\33.mpg");//上传
//ud.downloadFile("d:\\down\\");//下载,参数要带"\\"
//ud.clearDB();//清空文件所在的数据库表
} catch (Exception e) {
e.printStackTrace();
}
}
}