一个上传包的类


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

import javax.servlet.http.HttpServletRequest;

public class G_UPLOAD {

public static String a_path = "";
public static ArrayList<String> a_tmtList = new ArrayList<String>();
//public static HashSet<String> hs_id = new HashSet<String>();
public static HashMap<String,String> hm_id = new HashMap<String,String>();
public static BufferedReader bufferedreader = null;

public static void main(String[] args) {
// try {
// readfile("c:\\aaaaaa\\gimages");
// } catch (Exception e) {
// e.printStackTrace();
// }
}

public static String error = "";
public static String locate = "";
public static String tmpziploc = "/tmp/gimages.zip";
public static String tmpunzip = "/tmp/gimages/";
public static String imagespath = "/data/wwwroot/images/gimages/";

public static HashSet<String> upload(HttpServletRequest req) {
boolean result = true;
HashSet<String> res = new HashSet<String>();
FileOutputStream fos = null;
System.out.println("...................Stating..................");
try {
Hashtable ht = tools.StrProc.getUpload(req);
byte[] ppfile = (byte[]) ht.get("file1");
if (ppfile == null || ppfile.length == 0) {
//return true;
System.out.println("..................................... zip file too large..............");
res.add("true");
return res;
}

File old = new File(tmpziploc);
old.delete();

fos = new FileOutputStream(tmpziploc, true);
fos.write(ppfile);
fos.flush();

int length;
int length1;
String sDestPath = tmpunzip;
String sZipPathFile = tmpziploc;
ZipFile zip;
byte b[] = new byte[1024];
byte b1[] = new byte[1024];

deleteFolder(new File(sDestPath));

zip = new ZipFile(new File(sZipPathFile));
Enumeration enumeration = zip.entries();
ZipEntry zipEntry = null;
while (enumeration.hasMoreElements()) {
zipEntry = (ZipEntry) enumeration.nextElement();
File loadFile = new File(sDestPath + zipEntry.getName());
if (zipEntry.isDirectory()) {
loadFile.mkdirs();
} else {
if (!loadFile.getParentFile().exists())
loadFile.getParentFile().mkdirs();

OutputStream outputStream = new FileOutputStream(loadFile);
InputStream inputStream = zip.getInputStream(zipEntry);
// System.out.println(zipEntry.getName());
System.out.println("------zipEntry.getName(): "
+ zipEntry.getName());
while ((length = inputStream.read(b, 0, 1024)) != -1) {
outputStream.write(b, 0, length);
}
outputStream.close();
inputStream.close();
}
}

zip.close();

// 读文件
HashSet al = readfile(tmpunzip);
System.out.println("--------------------------------------- return's HashSet is: : "+al.size());

res = al;
} catch (Exception ex) {
ex.printStackTrace();
error = ex.getMessage() + " " + locate;
System.out.println("..................................... error:"+error);
//result = false;
res.add("false");
return res;
} finally {
try {
fos.close();
} catch (Exception iex) {

}
}
System.out.println("############################################# result returned: ............................."+result);
return res;
}


/**
* 读取某个文件夹下的所有文件夹和文件
* @throws FileNotFoundException
* @throws IOException
* @return HashSet
*/

public static HashSet readfile(String filepath) throws FileNotFoundException,IOException {
Connection conn31 = null;
PreparedStatement stmt_g = null;
PreparedStatement stmt_g_s = null;
HashSet<String> hs_id = new HashSet<String>();
try {
conn31 = mysql_31();
String str_n = "";
String str_e = "";
String t_path = "";
String str_hz = "";
String stemp;

int length1;
byte b1[] = new byte[1024];

// String n_path = "";
File file = new File(filepath);
if (file.isDirectory()) {
// System.out.println("嵌套文件夹");
String[] filelist = file.list();

for (int i = 0; i < filelist.length; i++) {
// File readfile = new File(filepath + "\\" + filelist[i]);
File readfile = new File(filepath + "/" + filelist[i]);
if (!readfile.isDirectory()) {
t_path = readfile.getAbsolutePath();
str_n = (readfile.getName()).substring(0, readfile.getName().length() - 4);
str_e = (readfile.getName()).substring(0,readfile.getName().length()).toLowerCase();
str_hz = str_e.substring(str_e.lastIndexOf("."), str_e.length());
// n_path = t_path.substring(0,t_path.length()-readfile.getName().length());
if (i == 0) {
a_path = t_path.substring(0, t_path.length() - readfile.getName().length());
}
// System.out.println(a_path);
// System.out.println("ID:" + str_n + ", " + str_e+ ", 后缀:" + str_hz + ", 路径: " + t_path);

String idfile = filepath.replace(tmpunzip, "").replace("/", "");
System.out.println(idfile);
if (t_path.contains(".txt") && str_hz.equals(".txt")) {

File f = new File(t_path);
try {
java.io.InputStream ios = new java.io.FileInputStream(f);
byte[] b = new byte[3];
ios.read(b);
ios.close();
if (b[0] == -17 && b[1] == -69 && b[2] == -65) {
System.out.println(f.getName() + "Code: UTF-8");

// bufferedreader = new BufferedReader(new FileReader(t_path));
String g_id = "";
String g_name = "";
String g_type = "";
String g_m = "";
String g_fee = "";
String g_com = "";
String g_de = "";
String g_le = "1";
int ii = 0;
FileInputStream fin = new FileInputStream(t_path);
InputStreamReader fileIn = new InputStreamReader(fin, "UTF-8");
BufferedReader infm = new BufferedReader(fileIn);

while ((stemp = infm.readLine()) != null) {
ii++;
stemp = stemp.trim().replaceAll(" ", "").replaceAll(" ", "").replace(":", ":");
System.out.println(stemp.substring(stemp.indexOf(":") + 1, stemp.length()));
stemp = stemp.substring(stemp.indexOf(":") + 1,stemp.length());
if (ii == 1) {
g_id = stemp;
if (!g_id.matches("\\d+") || g_id.length() <= 0) {
System.out.println("invalid ID....");
break;
}
// System.out.println("编号: "+g_id+", "+g_id.length());
}

}
if (g_id.length() <= 0) {
System.out.println("...............................failure..data...............................");
hs_id.add(idfile+".c");//txt文件格式不正确,可能属性值为空
} else {
if(idfile.equals(g_id)){
g_id = idfile;
}
String sql_s = "select game_id from game.T_GAME_STORE where game_id=?";
stmt_g_s = conn31.prepareStatement(sql_s);
stmt_g_s.setString(1, g_id);
//stmt_g.executeQuery();
if(!stmt_g_s.executeQuery().next()){
System.out.println("...............................inserting...............................");
String sql_in = "insert into game.T_GAME_STORE(game_id) values(?)";
stmt_g = conn31.prepareStatement(sql_in);
stmt_g.setString(1, g_id);
stmt_g.execute();

// System.out.println("/tmp/gimages/"+idfile+" "+"/data/wwwroot/images/gimages/"+idfile);
//copyDirectiory(tmpunzip + idfile, imagespath + idfile);
}else{
// update
System.out.println("...............................updating...............................: "+g_id);
String sql_up = "update game.T_GAME_STORE set game_name=? where game_id=?";
stmt_g = conn31.prepareStatement(sql_up);
stmt_g.setString(1, g_id);
stmt_g.executeUpdate();
}
copyDirectiory(tmpunzip + idfile, imagespath + idfile);

}


}else{
System.out.println(f.getName()+"Code maybe: ASCII");
hs_id.add(idfile+".b");//编码不是UTF-8
}
}catch(Exception e){
e.printStackTrace();
}
}

} else {
if (readfile.isDirectory()) {
String[] filelist2 = readfile.list();
//System.out.println(filelist[i]);
System.out.println("...............................file's length: "+filelist2.length);
if (filelist2.length >= 7) {
// readfile(filepath + "\\" + filelist[i]);
readfile(filepath + "/" + filelist[i]);
} else {
hs_id.add(filelist[i]+".a");// 文件不够,可能图片或txt文件缺失
System.out.println("...............................file isn't enough: "+filelist[i]+", file size: "+filelist2.length+"...............................");
}

}
}
}
}

} catch (Exception e) {
System.out.println("...............................readfile() Exception: " + e.getMessage());
e.printStackTrace();
} finally {
if (stmt_g != null) {
try {
stmt_g.close();
stmt_g = null;
} catch (SQLException e) {
e.printStackTrace();
stmt_g = null;
}
}
if (stmt_g_s != null) {
try {
stmt_g_s.close();
stmt_g_s = null;
} catch (SQLException e) {
e.printStackTrace();
stmt_g_s = null;
}
}
if (conn31 != null) {
try {
conn31.close();
conn31 = null;
} catch (SQLException e) {
e.printStackTrace();
conn31 = null;
}
}
}

return hs_id;
}

public static void deleteFolder(File dir) {
if (dir.exists()) {
File filelist[] = dir.listFiles();
int listlen = filelist.length;
for (int i = 0; i < listlen; i++) {
if (filelist[i].isDirectory()) {
deleteFolder(filelist[i]);
} else {
filelist[i].delete();
}
}
dir.delete();// 删除当前目录
}
}

public static void copyDirectiory(String sourceDir, String targetDir)
throws IOException {
// 新建目标目录
(new File(targetDir)).mkdirs();
// 获取源文件夹当前下的文件或目录
File[] file = (new File(sourceDir)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
// 源文件
File sourceFile = file[i];
// 目标文件
File targetFile = new File(new File(targetDir)
.getAbsolutePath()
+ File.separator + file[i].getName());
copyFile(sourceFile, targetFile);
}
if (file[i].isDirectory()) {
// 准备复制的源文件夹
String dir1 = sourceDir + "/" + file[i].getName();
// 准备复制的目标文件夹
String dir2 = targetDir + "/" + file[i].getName();
copyDirectiory(dir1, dir2);
}
}
}


public static void copyFile(File sourceFile, File targetFile)
throws IOException {
// 新建文件输入流并对它进行缓冲
FileInputStream input = new FileInputStream(sourceFile);
BufferedInputStream inBuff = new BufferedInputStream(input);

// 新建文件输出流并对它进行缓冲
FileOutputStream output = new FileOutputStream(targetFile);
BufferedOutputStream outBuff = new BufferedOutputStream(output);

// 缓冲数组
byte[] b = new byte[1024 * 5];
int len;
while ((len = inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
// 刷新此缓冲的输出流
outBuff.flush();

// 关闭流
inBuff.close();
outBuff.close();
output.close();
input.close();
}

public static void unRarFile(String targetPath, String absolutePath) {
try {
// 系统安装winrar的路径
String cmd = "C:\\Program Files\\WinRAR\\winrar.exe";
String unrarCmd = cmd + " x -r -p- -o+ " + absolutePath + " "
+ targetPath;

Runtime rt = Runtime.getRuntime();
Process pre = rt.exec(unrarCmd);
InputStreamReader isr = new InputStreamReader(pre.getInputStream());
BufferedReader bf = new BufferedReader(isr);
String line = null;
while ((line = bf.readLine()) != null) {
line = line.trim();
if ("".equals(line)) {
continue;
}
System.out.println(line);
}

bf.close();
} catch (Exception e) {
System.out.println("解压发生异常");
}
}

public void fileUpload(HttpServletRequest req) {

}

public static String to_utf8(String utf8) {
int len = utf8.length();
String[] s = new String[len];
// cn -> unicode
for (int i = 0; i < len; i++) {
char c = utf8.charAt(i);
s[i] = Integer.toString(c, 16);
// System.out.println(c + "\t\\u" + s[i]);
}
// System.out.println();
// unicode -> cn

for (int i = 0; i < len; i++) {
char c = (char) Integer.valueOf(s[i], 16).intValue();
// System.out.println("\\u" + s[i] + "\t" + c);
// System.out.println(c);
utf8 += c;
}
return utf8;
}

public static void unzipFile(String targetPath, String zipFilePath) {

try {
File zipFile = new File(zipFilePath);
InputStream is = new FileInputStream(zipFile);
ZipInputStream zis = new ZipInputStream(is);
ZipEntry entry = null;
System.out.println("开始解压:" + zipFile.getName() + "...");
while ((entry = zis.getNextEntry()) != null) {
String zipPath = entry.getName();
try {

if (entry.isDirectory()) {
File zipFolder = new File(targetPath + File.separator
+ zipPath);
if (!zipFolder.exists()) {
zipFolder.mkdirs();
}
} else {
File file = new File(targetPath + File.separator
+ zipPath);
if (!file.exists()) {
File pathDir = file.getParentFile();
pathDir.mkdirs();
file.createNewFile();
}

FileOutputStream fos = new FileOutputStream(file);
int bread;
while ((bread = zis.read()) != -1) {
fos.write(bread);
}
fos.close();
}
System.out.println("成功解压:" + zipPath);

} catch (Exception e) {
System.out.println("解压" + zipPath + "失败");
continue;
}
}
zis.close();
is.close();
System.out.println("解压结束");
} catch (Exception e) {
e.printStackTrace();
}

}

// 用JAVA自带的函数
public static boolean isNumeric(String str) {
for (int i = str.length(); --i >= 0;) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}

// mysql 数据库
private static Connection mysql_31() {
final String userName = "1111";
final String password = "1111";
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://localhost:3306/game";
conn = DriverManager.getConnection(url, userName, password);
} catch (Exception ex) {
ex.printStackTrace();
}
return conn;
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值