123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566 |
- package com.toolkit.file;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.io.StringWriter;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.SQLException;
- import java.util.Calendar;
- import javax.xml.transform.Transformer;
- import javax.xml.transform.TransformerException;
- import javax.xml.transform.TransformerFactory;
- import javax.xml.transform.dom.DOMSource;
- import javax.xml.transform.stream.StreamResult;
- import org.apache.log4j.Logger;
- import org.w3c.dom.Document;
- // TODO: Auto-generated Javadoc
- /**
- * The Class FileOperate.
- */
- public class FileOperate{
- /** The Constant log. */
- private final static Logger log = Logger.getLogger(FileOperate.class);
- /** The message. */
- private String message;
- /**
- * The Constructor.
- *
- * @author sun
- * @version 2009-7-17-14:04:29
- *
- * Instantiates a new file operate.
- */
- public FileOperate() {
- }
- /**
- * 读取文本文件内容
- *
- * @param filePathAndName
- * 带有完整绝对路径的文件名
- * @param encoding
- * 文本文件打开的编码方式
- * @return 返回文本文件的内容
- */
- @SuppressWarnings("resource")
- public String readTxt(String filePathAndName, String encoding) throws IOException {
- encoding = encoding.trim();
- StringBuffer str = new StringBuffer("");
- String st = "";
- try {
- FileInputStream fs = new FileInputStream(filePathAndName);
- InputStreamReader isr;
- if (encoding.equals("")) {
- isr = new InputStreamReader(fs);
- } else {
- isr = new InputStreamReader(fs, encoding);
- }
- BufferedReader br = new BufferedReader(isr);
- try {
- String data = "";
- while ((data = br.readLine()) != null) {
- str.append(data + " ");
- }
- } catch (Exception e) {
- str.append(e.toString());
- }
- st = str.toString();
- } catch (IOException es) {
- st = "";
- }
- return st;
- }
- /**
- * 新建文件
- *
- * @param filePathAndName
- * 文本文件完整绝对路径及文件名
- * @param fileContent
- * 文本文件内容
- * @return
- */
- public void createFile(String filePathAndName, String fileContent) {
- try {
- String filePath = filePathAndName;
- filePath = filePath.toString();
- File myFilePath = new File(filePath);
- if (!myFilePath.exists()) {
- myFilePath.createNewFile();
- }
- FileWriter resultFile = new FileWriter(myFilePath);
- PrintWriter myFile = new PrintWriter(resultFile);
- String strContent = fileContent;
- myFile.println(strContent);
- myFile.close();
- resultFile.close();
- } catch (Exception e) {
- message = "创建文件操作出错";
- }
- }
- /**
- * 有编码方式的文件创建
- *
- * @param filePathAndName
- * 文本文件完整绝对路径及文件名
- * @param fileContent
- * 文本文件内容
- * @param encoding
- * 编码方式 例如 GBK 或者 UTF-8
- * @return
- */
- public void createFile(String filePathAndName, String fileContent, String encoding) {
- try {
- String filePath = filePathAndName;
- filePath = filePath.toString();
- File myFilePath = new File(filePath);
- if (!myFilePath.exists()) {
- myFilePath.createNewFile();
- }
- PrintWriter myFile = new PrintWriter(myFilePath, encoding);
- String strContent = fileContent;
- myFile.println(strContent);
- myFile.close();
- } catch (Exception e) {
- message = "创建文件操作出错";
- }
- }
- /**
- * 删除文件
- *
- * @param filePathAndName
- * 文本文件完整绝对路径及文件名
- * @return Boolean 成功删除返回true遭遇异常返回false
- */
- public boolean delFile(String filePathAndName) {
- boolean bea = false;
- try {
- String filePath = filePathAndName;
- File myDelFile = new File(filePath);
- if (myDelFile.exists()) {
- myDelFile.delete();
- bea = true;
- } else {
- bea = false;
- message = (filePathAndName + "删除文件操作出错");
- }
- } catch (Exception e) {
- message = e.toString();
- }
- return bea;
- }
- /**
- * 删除文件夹
- *
- * @param folderPath
- * 文件夹完整绝对路径
- * @return
- */
- public void delFolder(String folderPath) {
- try {
- delAllFile(folderPath); // 删除完里面所有内容
- String filePath = folderPath;
- filePath = filePath.toString();
- java.io.File myFilePath = new java.io.File(filePath);
- myFilePath.delete(); // 删除空文件夹
- } catch (Exception e) {
- message = ("删除文件夹操作出错");
- }
- }
- /**
- * 删除指定文件夹下所有文件
- *
- * @param path
- * 文件夹完整绝对路径
- * @return
- * @return
- */
- public boolean delAllFile(String path) {
- boolean bea = false;
- File file = new File(path);
- if (!file.exists()) {
- return bea;
- }
- if (!file.isDirectory()) {
- return bea;
- }
- String[] tempList = file.list();
- File temp = null;
- for (int i = 0; i < tempList.length; i++) {
- if (path.endsWith(File.separator)) {
- temp = new File(path + tempList[i]);
- } else {
- temp = new File(path + File.separator + tempList[i]);
- }
- if (temp.isFile()) {
- temp.delete();
- }
- if (temp.isDirectory()) {
- delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
- delFolder(path + "/" + tempList[i]);// 再删除空文件夹
- bea = true;
- }
- }
- return bea;
- }
- /**
- * 复制单个文件
- *
- * @param oldPathFile
- * 准备复制的文件源
- * @param newPathFile
- * 拷贝到新绝对路径带文件名
- * @return
- */
- @SuppressWarnings("resource")
- public void copyFile(String oldPathFile, String newPathFile) {
- try {
- int bytesum = 0;
- int byteread = 0;
- File oldfile = new File(oldPathFile);
- if (oldfile.exists()) { // 文件存在时
- InputStream inStream = new FileInputStream(oldPathFile); // 读入原文件
- FileOutputStream fs = new FileOutputStream(newPathFile);
- byte[] buffer = new byte[1444];
- while ((byteread = inStream.read(buffer)) != -1) {
- bytesum += byteread; // 字节数 文件大小
- log.info(bytesum);
- fs.write(buffer, 0, byteread);
- }
- inStream.close();
- }
- } catch (Exception e) {
- message = ("复制单个文件操作出错");
- }
- }
- /**
- * 复制整个文件夹的内容
- *
- * @param oldPath
- * 准备拷贝的目录
- * @param newPath
- * 指定绝对路径的新目录
- * @return
- */
- public void copyFolder(String oldPath, String newPath) {
- try {
- new File(newPath).mkdirs(); // 如果文件夹不存在 则建立新文件夹
- File a = new File(oldPath);
- String[] file = a.list();
- File temp = null;
- for (int i = 0; i < file.length; i++) {
- if (oldPath.endsWith(File.separator)) {
- temp = new File(oldPath + file[i]);
- } else {
- temp = new File(oldPath + File.separator + file[i]);
- }
- if (temp.isFile()) {
- FileInputStream input = new FileInputStream(temp);
- FileOutputStream output = new FileOutputStream(newPath + "/"
- + (temp.getName()).toString());
- byte[] b = new byte[1024 * 5];
- int len;
- while ((len = input.read(b)) != -1) {
- output.write(b, 0, len);
- }
- output.flush();
- output.close();
- input.close();
- }
- if (temp.isDirectory()) {// 如果是子文件夹
- copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
- }
- }
- } catch (Exception e) {
- message = "复制整个文件夹内容操作出错";
- }
- }
- /**
- * 读取整个目录的文件名
- *
- * @param path
- * 准备读取的目录
- * @return
- */
- public static void readFolder(String path, Connection con) {
- try {
- File a = new File(path);
- String[] file = a.list();
- File temp = null;
- for (int i = 0; i < file.length; i++) {
- if (path.endsWith(File.separator)) {
- temp = new File(path + file[i]);
- } else {
- temp = new File(path + File.separator + file[i]);
- }
- if (temp.isFile()) {
- String sql = "insert into imgUrl values('" + path + "/"
- + temp.getName().toString() + "')";
- PreparedStatement ps = con.prepareStatement(sql);
- ps.execute();
- ps.close();
- // WriteToFile(path + temp.getName().toString(),
- // "D:/name.txt");
- // FileInputStream input = new FileInputStream(temp);
- // FileOutputStream output = new FileOutputStream(newPath +
- // "/" +
- // (temp.getName()).toString());
- // byte[] b = new byte[1024 * 5];
- // int len;
- // while ((len = input.read(b)) != -1) {
- // output.write(b, 0, len);
- // }
- // output.flush();
- // output.close();
- // input.close();
- }
- if (temp.isDirectory()) {// 如果是子文件夹
- readFolder(path + "/" + file[i], con);
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 移动文件
- *
- * @param oldPath
- * @param newPath
- * @return
- */
- public void moveFile(String oldPath, String newPath) {
- copyFile(oldPath, newPath);
- delFile(oldPath);
- }
- /**
- * 移动目录
- *
- * @param oldPath
- * @param newPath
- * @return
- */
- public void moveFolder(String oldPath, String newPath) {
- copyFolder(oldPath, newPath);
- delFolder(oldPath);
- }
- /**
- * 把从DOM中获得的DOCUMENT对象存放到制定的XML文件路径中
- *
- * @param doc
- * @param filePath
- * @return
- * @throws TransformerException
- */
- public boolean saveDocumentFromDomToXMLFile(Document doc, String filePath)
- throws TransformerException {
- /**
- * dom对象保存到制定的XML文件 filePath 中
- */
- StringWriter sw = new StringWriter();
- TransformerFactory transformerfactory = TransformerFactory.newInstance();
- Transformer transformer = transformerfactory.newTransformer();
- StreamResult result = new StreamResult(sw);
- DOMSource source = new DOMSource(doc.getDocumentElement());
- transformer.transform(source, result);
- String s = sw.toString();
- log.info(s);
- FileOutputStream fo = null;
- try {
- fo = new FileOutputStream(filePath);
- fo.write(s.getBytes("utf-8"));
- fo.close();// 关闭
- } catch (IOException e) {
- e.printStackTrace();
- }
- return true;
- }
- /**
- * 有编码方式的文件创建
- *
- * @param filePathAndName
- * 文本文件完整绝对路径及文件名
- * @param fileContent
- * 文本文件内容
- * @param encoding
- * 编码方式 例如 GBK 或者 UTF-8
- * @return
- */
- public boolean createFile(String fileName, String folderPath, String fileContent,
- String encoding, boolean bbakup) {
- try {
- /**
- * 第一步:先判断文件夹是否存在,不存在逐级创建文件夹
- */
- File myFilePath = new File(folderPath);
- log.info("folderPath = " + folderPath);
- if (!myFilePath.exists()) {
- createFolder(folderPath);
- }
- /**
- * 第二步:把文件写入到指定的文件中
- */
- String filePath = folderPath + "/" + fileName;
- filePath = filePath.toString();
- myFilePath = new File(filePath);
- if (!myFilePath.exists()) {
- myFilePath.createNewFile();
- } else {
- if (bbakup) {
- Calendar calendar = Calendar.getInstance();
- java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
- myFilePath.renameTo(new File(filePath.replace(".",
- df.format(calendar.getTime()) + ".")));
- }
- }
- PrintWriter myFile = new PrintWriter(myFilePath, encoding);
- String strContent = fileContent;
- myFile.println(strContent);
- myFile.close();
- return true;
- }
- catch (Exception e) {
- message = "创建文件操作出错";
- }
- return false;
- }
- /**
- * 新建目录
- *
- * @param folderPath
- * 目录
- * @return 返回目录创建后的路径
- */
- public static boolean createFolder(String folderPath) {
- try {
- log.info("folderPath = " + folderPath);
- File myFilePath = new File(folderPath);
- if (!myFilePath.exists()) {
- String[] s = folderPath.split("/");
- String tempForder = s[0];
- for (int i = 1; i < s.length; i++) {
- tempForder = tempForder + "/" + s[i];
- File forderFile = new File(tempForder);
- // log.info("folderPath = "+tempForder);
- if (!forderFile.exists()) {
- forderFile.mkdir();
- }
- }
- }
- } catch (Exception e) {
- log.error(e.toString());
- }
- return true;
- }
- /**
- * @return
- */
- public String getMessage() {
- return this.message;
- }
- /**
- * Write to file.
- *
- * @param str
- * 要写入的字符串
- * @param path
- * 要写入的文件路径和文件名字
- *
- * @return true, if successful
- * @author sun
- *
- * @version 2009-7-17-14:04:29
- *
- * Write to file.
- */
- public static boolean WriteToFile(String str, String path) {
- boolean result = false;
- try {
- FileWriter fw = new FileWriter(new File(path), true);
- BufferedWriter bw = new BufferedWriter(fw);
- bw.write(str, 0, str.length());
- bw.newLine();
- bw.close();
- result = true;
- } catch (IOException e) {
- log.info(e.getMessage(), e);
- }
- return result;
- }
- public static void main(String[] args) {
- // String fs = "D:/ws/bjglweb/WebContent/page/system/sun/ff/dd";
- // createFolder(fs);
- Connection connection = null;
- if (connection == null) {
- try {
- Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
- connection = DriverManager
- .getConnection("jdbc:sqlserver://192.168.100.183;databaseName=TrueMapDB;user=sa;password=sinosoft183");
- readFolder("\\\\192.168.100.178/g$/宁波数据发布/Image/NormalImage/000261/2008",
- connection);
- connection.close();
- } catch (ClassNotFoundException e) {
- log.error(e);
- } catch (SQLException e) {
- log.error(e);
- }
- }
- }
- }
|