Swing中文件选择器
程序员文章站
2022-05-19 18:57:47
...
今天同事开发了一些导入导出功能,我不经意间看到了选择器。感觉挺不错的,然后发了上来
package com.deppon.util;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;
public class ChooserTest {
/**
* @param args
*/
public static void main(String[] args) {
chooserSomething();
}
/**
* @desc 通过弹出的框框进行选择文件
* @author 张兴旺
* @date 2012-12-27
*/
public static void chooserSomething(){
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
FileFilter fileFilter = new FileFilter() {
@Override
public boolean accept(File pathname) {
String name = pathname.getName().toLowerCase();
if (name.endsWith(".png") || name.endsWith(".jpg")
|| name.endsWith(".bmp") || name.endsWith(".gif")
|| pathname.isDirectory()) {
return true;
}
return false;
}
@Override
public String getDescription() {
return "图片文件";
}
};
chooser.addChoosableFileFilter(fileFilter);
int result = chooser.showOpenDialog(null);
if(result == JFileChooser.APPROVE_OPTION){
File selectedImage = chooser.getSelectedFile();
//以下可以作必要的动作,比如上传到数据库里面,则要有一个转换成Byte字节文件
System.out.println(selectedImage.getAbsolutePath());
System.out.println(getByteFromFile(selectedImage).length);
byte[] image = getByteFromFile(selectedImage);
Connection con = JdbcUtil.getConnection();
PreparedStatement psmt = null;
ByteArrayInputStream bins = null;
String sql = "insert into tbbyte(idtbbyte,byteimage) values(?,?)";
try {
bins = new ByteArrayInputStream(getByteFromFile(selectedImage));
psmt = con.prepareStatement(sql);
psmt.setInt(1, 1);
psmt.setBinaryStream(2, bins, image.length);
// if(!psmt.execute()){
// bins.close();
// psmt.close();
// }
psmt.execute();
bins.close();
psmt.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
JdbcUtil.closeConnection(con, psmt, null);
}
}
}
/**
* @desc 将文件转换成字节流,可以方便的存储到数据库中
* @author 张兴旺
* @date 2012-12-27
* @param file
* @return
*/
private static byte[] getByteFromFile(File file){
if(file != null){
int size = (int) file.length();
FileInputStream fs = null;
try {
fs = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] bts = null;
if(size>0){
bts = new byte[size];
try {
fs.read(bts);
} catch (IOException e) {
e.printStackTrace();
}
return bts;
}
}
return null;
}
}
下一篇: 到底该如何经营好自己的婚姻呢?