`

Java File工具类附带MYSQL SQL转HSQL SQL字符串处理

 
阅读更多
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Random;
import java.util.Vector;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * 
 * 文件操作的工具类
 * 
 * @version [8.0,2011-5-20 下午04:29:53]
 */
public class FileUtil {

    private static final int DEFAULT_READING_SIZE = 8192;

    public static void copyFile(File sourceFile, File destFile) throws IOException {
        if (!destFile.exists()) {
            File parent = destFile.getParentFile();
            if (parent != null) {
                if (!parent.exists()) {
                    parent.mkdirs();
                }
            }
            destFile.createNewFile();
        }
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(sourceFile);
            out = new FileOutputStream(destFile);
            copy(in, out);
        } finally {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
        }
    }

    public static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = in.read(buf, 0, buf.length)) != -1) {
            out.write(buf, 0, len);
        }
    }

    public static void writeFile(File file, byte[] contents) throws IOException {
        if (!file.exists()) {
            file.createNewFile();
        }
        if (!file.isFile()) {
            throw new IOException("File to be written not exist, file path : " + file.getAbsolutePath());
        }
        FileOutputStream fileOut = null;
        BufferedOutputStream bOutput = null;
        try {
            fileOut = new FileOutputStream(file);
            bOutput = new BufferedOutputStream(fileOut);
            bOutput.write(contents);
            bOutput.flush();
        } finally {
            if (fileOut != null) {
                try {
                    fileOut.close();
                } catch (IOException e) {
                }
            }
            if (bOutput != null) {
                try {
                    bOutput.close();
                } catch (IOException e) {
                }
            }
        }

    }

    public static byte[] readFileContent(File file) throws IOException {
        if (!file.exists() || !file.isFile()) {
            throw new IOException("File to be readed not exist, file path : " + file.getAbsolutePath());
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        FileInputStream in = new FileInputStream(file);
        byte[] contents = null;
        try {
            copy(in, out);
            contents = out.toByteArray();
        } catch (IOException e) {
            throw e;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                };
            }

        }
        return contents;
    }

    public static String readFileContentAsString(File file) throws IOException {
        return readFileContentAsString(file, null);
    }

    public static String readFileContentAsString(File file, String charsetName) throws IOException {
        if (!file.exists() || !file.isFile()) {
            throw new IOException("File to be readed not exist, file path : " + file.getAbsolutePath());
        }

        FileInputStream fileIn = null;
        InputStreamReader inReader = null;
        BufferedReader bReader = null;
        try {
            fileIn = new FileInputStream(file);
            inReader = charsetName == null ? new InputStreamReader(fileIn) : new InputStreamReader(fileIn, charsetName);
            bReader = new BufferedReader(inReader);
            StringBuffer content = new StringBuffer();
            char[] chBuffer = new char[1024];
            int readedNum = -1;
            while ((readedNum = bReader.read(chBuffer)) != -1) {
                content.append(chBuffer, 0, readedNum);
            }

            return content.toString();
        } finally {
            if (fileIn != null) {
                try {
                    fileIn.close();
                } catch (IOException e) {
                }
            }

            if (bReader != null) {
                try {
                    bReader.close();
                } catch (IOException e) {
                }
            }
        }
    }

    /**
     * 追加内容到文件里,会覆盖
     * 
     * @param file
     * @param content
     * @throws IOException
     */
    public static void writeStringAsFileContent(File file, String content) throws IOException {
        writeStringAsFileContent(file, content, null);
    }

    public static void writeStringAsFileContent(File file, String content, String charsetName) throws IOException {
        if (!file.exists() || !file.isFile()) {
            throw new IOException("File to be written not exist, file path : " + file.getAbsolutePath());
        }

        FileOutputStream fileOut = null;
        OutputStreamWriter outWriter = null;
        BufferedWriter bWriter = null;
        try {
            fileOut = new FileOutputStream(file);
            outWriter = charsetName == null ? new OutputStreamWriter(fileOut)
                                           : new OutputStreamWriter(fileOut, charsetName);
            bWriter = new BufferedWriter(outWriter);
            bWriter.write(content);
            bWriter.flush();
        } finally {
            if (fileOut != null) {
                try {
                    fileOut.close();
                } catch (IOException e) {
                }
            }

            if (bWriter != null) {
                try {
                    bWriter.close();
                } catch (IOException e) {
                }
            }
        }
    }

    /**
     * 删除指定目录及其子目录下的指定文件
     * 
     * @param dir
     * @param filter
     * @throws IOException
     */
    public static void deleteWholeDirectory(File dir) throws IOException {
        if (!dir.exists() || !dir.isDirectory()) {
            throw new IOException("Directory to be deleted not exist, directory path : " + dir.getAbsolutePath());
        }

        File[] children = dir.listFiles();
        for (File child : children) {
            if (child.isDirectory()) {
                deleteWholeDirectory(child);
            } else {
                child.delete();
            }
        }

        dir.delete();
    }

    /**
     * 删除指定目录及其子目录下的指定文件
     * 
     * @param dir
     * @param filter
     * @throws IOException
     */
    public static void deleteFilesInWholeDirectory(File dir, FilenameFilter filter) throws IOException {
        if (!dir.exists() || !dir.isDirectory()) {
            throw new IOException("Directory to be deleted not exist, directory path : " + dir.getAbsolutePath());
        }

        File[] children = dir.listFiles(filter);
        for (File child : children) {
            if (child.isDirectory()) {
                deleteFilesInWholeDirectory(child, filter);
            } else {
                child.delete();
            }
        }

        dir.delete();
    }

    /**
     * 根据一个流计算出MD5,不负责关闭该流
     * 
     * @param inputStream
     * @return
     * @throws IOException
     */
    public final static String md5(InputStream inputStream) throws IOException {
        try {
            BufferedInputStream in = new BufferedInputStream(inputStream);
            byte[] bytes = new byte[0];
            int count = 1;
            while (count != -1) {
                byte[] temp = new byte[1024 * 8];
                count = in.read(temp);
                byte[] full = new byte[bytes.length + temp.length];
                System.arraycopy(bytes, 0, full, 0, bytes.length);
                System.arraycopy(temp, 0, full, bytes.length, temp.length);
                bytes = full;
            }

            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(bytes);
            byte[] md = mdTemp.digest();
            return StringUtil.getHexDigitsString(md);
        } catch (NoSuchAlgorithmException ex) {
            // will not happen
            return null;
        }
    }

    public final static String md5(File file) throws IOException {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            return md5(fis);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    /**
     * 从XML文件中获取字符串内容
     * 
     * @param xmlFilePath
     * @return
     * @throws IOException
     */
    public static String getStringFromXMLFile(String xmlFilePath) throws IOException {
        File file = new File(xmlFilePath);
        return getStringFromXMLFile(file);
    }

    /**
     * 从XML文件中获取字符串内容
     * 
     * @param xmlFile
     * @return
     * @throws IOException
     */
    public static String getStringFromXMLFile(File xmlFile) throws IOException {
        String temp = "";
        String result = "";
        if (xmlFile.exists()) {
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader(xmlFile));
                while ((temp = reader.readLine()) != null) {
                    result = result + temp;
                }
            } catch (FileNotFoundException e) {
                throw new FileNotFoundException("file not found");
            } catch (IOException e) {
                throw new IOException();
            } finally {
                try {
                    reader.close();
                    reader = null;
                } catch (IOException e) {
                }
            }

            return result;
        } else {
            return null;
        }

    }

    /**
     * 
     * @param filePath 路径
     * @param isExt 是否需要扩展名(如果有的话)
     * @return
     */
    public static String getFileNameFromPath(String filePath, boolean isExt) {
        File file = new File(filePath);
        return getFileNameFromPath(file, isExt);

    }

    // 不带扩展名
    public static String getFileNameFromPath(String filePath) {
        File file = new File(filePath);
        return getFileNameFromPath(file, false);

    }

    public static String getFileNameFromPath(File file, boolean isExt) {

        String filePath = file.getAbsolutePath();

        int begin = filePath.lastIndexOf(File.separator);
        int end = filePath.lastIndexOf(".");

        String fileName = null;
        // 处理没有扩展名的文件
        if (end == -1 || end < begin) {
            fileName = filePath.substring(begin + 1);
        } else {
            if (isExt) {
                fileName = filePath.substring(begin + 1);
            } else {
                fileName = filePath.substring(begin + 1, end);
            }
        }
        return fileName;
    }

    public static boolean exists(URL url) {
        // check if a file exists
        if (url.getProtocol().equals("file")) {
            File f = new File(url.getFile());
            return f.exists();
        }

        // check if a jar file entry exists
        if (url.getProtocol().equals("jar")) {
            String spec = url.getFile();

            if (spec.startsWith("file:")) {
                int separator = spec.indexOf('!');
                if (separator == -1) {
                    return false;
                }

                String jarFileName = spec.substring(5, separator++);
                String entryName = null;

                // if ! is the last letter of the inner URL, entry not exist
                if (++separator != spec.length()) {
                    entryName = spec.substring(separator, spec.length());
                } else {
                    return false;
                }

                try {
                    JarFile jarFile = new JarFile(jarFileName);
                    JarEntry jarEntry = (JarEntry) jarFile.getEntry(entryName);
                    jarFile.close();
                    return jarEntry != null;
                } catch (IOException ex) {
                    return false;
                }
            }
        }

        // check if a resource exists
        try {
            InputStream is = url.openStream();
            is.close();
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    /**
     * 拷贝隐藏文件(文件名以.开头的文件)
     * 
     * @param source
     * @param dest
     * @throws IOException
     */
    public static void copyFilesIngoreHiddenFiles(File source, File dest) throws IOException {
        if (source != null /*&& source.exists()*/&& dest != null /*&& dest.exists()*/) {
            if (!source.getName().startsWith(".")) {
                copyFile2(source, dest);

                if (source.isDirectory()) {
                    File[] list = source.listFiles();
                    if (list != null) {
                        for (File file : list) {
                            copyFilesIngoreHiddenFiles(file, new File(dest.getAbsolutePath() + File.separator
                                                                      + file.getName()));
                        }
                    }
                }
            }
        }
    }

    /**
     * 复制文件夹
     * 
     * @throws IOException
     */
    public static void copyFolder(File srcDir, File destDir, List<?> excludedList) throws IOException {
        if (destDir == null || !destDir.exists()) {
            throw new FileNotFoundException("File destDir not existed");
        }
        if (srcDir == null || !srcDir.exists()) {
            throw new FileNotFoundException("File srcDir not existed");
        }
        File[] files = srcDir.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (excludedList != null && excludedList.contains(files[i])) {
                continue;
            }
            String fileName = files[i].getName();
            if (files[i].isFile()) {
                copyFileToDir(files[i], destDir);
            } else {
                File file = new File(destDir, fileName);
                file.mkdir();
                copyFolder(files[i], file, excludedList);
            }
        }
    }

    public static void copyFileToDir(File sourceFile, File destDir) throws IOException {
        String name = sourceFile.getName();
        File destFile = new File(destDir, name);
        if (sourceFile.isDirectory()) {
            destFile.mkdirs();
            return;
        }
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(sourceFile);
            out = new FileOutputStream(destFile);
            copy(in, out);
        } finally {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
        }
    }

    public static void copyFile2(File sourceFile, File destFile) throws IOException {
        if (sourceFile.isDirectory()) {
            destFile.mkdirs();
            return;
        }
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(sourceFile);
            out = new FileOutputStream(destFile);
            copy(in, out);
        } finally {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
        }
    }

    public static void copyFile(File sourceFile, File destDir, String newFileName) throws IOException {
        File destFile = new File(destDir, newFileName);
        if (sourceFile.isDirectory()) {
            destFile.mkdirs();
            return;
        }
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(sourceFile);
            out = new FileOutputStream(destFile);
            copy(in, out);
        } finally {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
        }

    }

    public static byte[] toByteArray(String path) throws IOException {
        File file = new File(path);
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            in.read(data);
            return data;
        } finally {
            in.close();
        }
    }

    /**
     * 
     * @param sourceDir
     * @param destDir
     * @param excludedDirName
     * @throws IOException
     */
    public static void copyDir(File sourceDir, File destDir, String excludedDirName) throws IOException {
        copyDir(sourceDir, destDir, true, excludedDirName);
    }

    public static void copyDir(File from, File to) throws IOException {
        copyDir(from, to, true, null);
    }

    public static void copyDir(File from, File to, boolean includeSubdirs) throws IOException {
        copyDir(from, to, includeSubdirs, null);
    }

    public static void copyDir(File from, File to, boolean includeSubdirs, String excludedDirName) throws IOException {
        if (!to.exists()) {
            to.mkdirs();
        }
        if (from == null || !from.isDirectory() || !to.isDirectory())
            return;
        File fs[] = from.listFiles();
        if (fs == null)
            return;
        for (int i = 0; i < fs.length; i++) {
            String n = fs[i].getName();
            File c = new File(to, n);
            if (fs[i].isDirectory() && !includeSubdirs)
                continue;
            if (fs[i].isDirectory()) {
                if (fs[i].getName().equals(excludedDirName)) {
                    continue;
                }
                c.mkdirs();
                copyDir(fs[i], c, includeSubdirs, excludedDirName);
                continue;
            }
            copyFileToDir(fs[i], to);
        }
    }

    public static File makeTempdir() throws IOException {
        return makeTempDir((File) null, null, null);
    }

    public static File makeTempDir(File parentDir, String prefix, String suffix) throws IOException {
        if (suffix == null)
            suffix = ".tmp";
        File tmpdir = null;
        if (parentDir == null) {
            tmpdir = new File(System.getProperty("java.io.tmpdir", "/temp"));
        } else {
            tmpdir = parentDir;
        }
        int counter = new Random().nextInt() & 0xffff;
        File f;
        do {
            counter++;
            f = new File(tmpdir, prefix + Integer.toString(counter) + suffix);
        } while (f.exists() || !f.mkdirs());
        return f;
    }

    public static File makeTempDir(String parentDir, String prefix, String suffix) throws IOException {
        File fileParentDir = null;
        if (parentDir != null)
            fileParentDir = new File(System.getProperty("java.io.tmpdir", "/temp"), parentDir);
        return makeTempDir(fileParentDir, prefix, suffix);
    }

    public static File getTempFile(File parentDir) {
        if (parentDir == null)
            parentDir = new File(System.getProperty("java.io.tmpdir", "/temp"));
        int counter = new Random().nextInt() & 0xffff;
        File f;
        do {
            counter++;
            f = new File(parentDir, "tempfile" + Integer.toString(counter));
        } while (f.exists());
        return f;
    }

    /**
     * get temp folder
     * 
     * @return the temp folder may be null
     */
    public static File getTempFolder() {
        File parentDir = new File(System.getProperty("java.io.tmpdir", "/temp"));
        int counter = new Random().nextInt() & 0xffff;
        File f = null;
        do {
            counter++;
            f = new File(parentDir, "tempfolder" + Integer.toString(counter));
        } while (f.exists());
        f.mkdir();
        return f;
    }

    public static void unpackZipFile(File zipFile, File dir) throws IOException {
        InputStream fis = new FileInputStream(zipFile);
        ZipInputStream zis = new ZipInputStream(fis);

        try {
            for (ZipEntry e = zis.getNextEntry(); e != null; e = zis.getNextEntry()) {
                File f = new File(dir, e.getName());
                if (e.isDirectory()) {
                    if (!f.exists() && !f.mkdirs()) {
                        throw new IOException("Cannot make directory " + f.getPath());
                    }
                } else {
                    File d = f.getParentFile();
                    if (d != null && !d.exists() && !d.mkdirs()) {
                        throw new IOException("Cannot make directory " + d.getPath());
                    }

                    OutputStream out = new FileOutputStream(f);
                    copy(zis, out);
                    out.close();
                }
            }
        } finally {
            zis.close();
            fis.close();
        }
    }

    public static void makeJarFile(File jarFile, File dir) throws IOException {
        makeJarFile(jarFile, dir, null);
    }

    /**
     * 
     * @param jarFile
     * @param dir
     * @param excludedList java.io.File
     * @throws IOException
     */
    public static void makeJarFile(File jarFile, File dir, Vector excludedList) throws IOException {
        /*
         * Create output jar file
         */
        OutputStream fos = new FileOutputStream(jarFile);
        ZipOutputStream zos = new ZipOutputStream(fos);

        /*
         * Add entries to jar file
         */
        try {
            addToJar(zos, dir, excludedList, new Vector());
        } finally {
            zos.close();
            fos.close();
        }
    }

    public static void addToJar(ZipOutputStream zos, File dir, Vector excludedList, Vector entriesAdded) throws IOException {
        /*
         * Expands list of files to process into full list of all files that can
         * be found by recursively descending directories.
         */
        Vector v = new Vector();
        expand(dir, dir.list(), excludedList, v);

        /*
         * Add entries to jar file
         */
        String path = dir.getPath();
        if (!path.endsWith(File.separator)) {
            path = path + File.separator;
        }
        path = path.replace(File.separatorChar, '/');
        for (int i = 0; i < v.size(); i++) {
            addFile(zos, path, (File) v.elementAt(i), entriesAdded);
        }
    }

    private static void expand(File dir, String[] files, Vector excludeList, Vector v) {
        if (files == null) {
            return;
        }
        for (int i = 0; i < files.length; i++) {
            File f = new File(dir, files[i]);
            if (excludeList == null || !excludeList.contains(f)) {
                if (f.isFile()) {
                    v.addElement(f);
                } else if (f.isDirectory()) {
                    v.addElement(f);
                    expand(f, f.list(), excludeList, v);
                }
            }
        }
    }

    private static void addFile(ZipOutputStream zos, String path, File file, Vector entriesAdded) throws IOException {
        String name = file.getPath();
        boolean isDir = file.isDirectory();

        if (isDir) {
            if (!name.endsWith(File.separator)) {
                name = name + File.separator;
            }
        }
        name = name.replace(File.separatorChar, '/');
        if (name.startsWith(path)) {
            name = name.substring(path.length());
        }
        if (entriesAdded.contains(name)) {
            return;
        }

        long size = isDir ? 0 : file.length();
        ZipEntry e = new ZipEntry(name);
        e.setTime(file.lastModified());
        if (size == 0) {
            e.setMethod(ZipEntry.STORED);
            e.setSize(0);
            e.setCrc(0);
        }
        zos.putNextEntry(e);
        if (!isDir) {
            InputStream in = new FileInputStream(file);
            copy(in, zos);
            in.close();
        }
        zos.closeEntry();
        entriesAdded.addElement(name);
    }

    public static String getFileNameWithoutExt(String filePath) {
        filePath = filePath.replace('\\', '/');
        int pos = filePath.lastIndexOf('/');
        String fileName = filePath.substring(pos + 1);
        int pos2 = fileName.lastIndexOf('.');
        if (pos2 == -1) {
            return fileName;
        } else {
            return fileName.substring(0, pos2);
        }
    }

    public static boolean isZipFile(File file) {
        try {
            ZipFile zip = new ZipFile(file);
            zip.close();
            return true;
        } catch (IOException ex) {
            return false;
        }
    }

    public static void removeDir(File dir) {
        if (dir.isDirectory()) {
            removeFile(dir);
        }
        dir.delete();
    }

    public static void removeFile(File file) {
        if (file.isFile()) {

        } else if (file.isDirectory()) {
            // Recursively remove all files in subdirectory.
            String list[] = file.list();
            if (list != null) {
                for (int i = 0; i < list.length; i++) {
                    File f = new File(file, list[i]);
                    removeFile(f);
                }
            }
        }
        file.delete();
    }

    public static URL getFileURL(File file) {
        try {
            file = file.getCanonicalFile();
        } catch (IOException e) {
        }
        String path = file.getAbsolutePath();
        if (File.separatorChar != '/') {
            path = path.replace(File.separatorChar, '/');
        }
        if (!path.startsWith("/")) {
            path = "/" + path;
        }
        if (!path.endsWith("/") && file.isDirectory()) {
            path = path + "/";
        }
        try {
            return new URL("file", "", -1, path);
        } catch (MalformedURLException e) {
            // Should never happen since we specified the protocol
            throw new InternalError();
        }
    }

    /**
     * 读取文件内容并将其转换为String类型
     * 
     * @param file
     * @return
     * @throws IOException
     */
    public static String getFileStringContent(File file) throws IOException {
        return new String(getFileByteContent(file));
    }

    /**
     * 读取文件内容并按指定字符编码类型来将其转换成String类型
     * 
     * @param file
     * @param charsetName
     * @return
     * @throws IOException
     */
    public static String getFileStringContent(File file, String charsetName) throws IOException {
        return new String(getFileByteContent(file), charsetName);
    }

    /**
     * 读取InputStream留的内容并将其转换为String类型
     * 
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static String getInputStreamStringContent(InputStream inputStream) throws IOException {
        return new String(getInputStreamAsByteArray(inputStream, -1));
    }

    /**
     * Returns the contents of the given file as a byte array.
     * 
     * @throws IOException if a problem occured reading the file.
     */
    public static byte[] getFileByteContent(File file) throws IOException {
        InputStream stream = null;
        try {
            stream = new BufferedInputStream(new FileInputStream(file));
            return getInputStreamAsByteArray(stream, (int) file.length());
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    // ignore
                }
            }
        }
    }

    /**
     * Returns the given input stream's contents as a byte array. If a length is specified (ie. if length != -1), only
     * length bytes are returned. Otherwise all bytes in the stream are returned. Note this doesn't close the stream.
     * 
     * @throws IOException if a problem occured reading the stream.
     */
    public static byte[] getInputStreamAsByteArray(InputStream stream, int length) throws IOException {
        byte[] contents;
        if (length == -1) {
            contents = new byte[0];
            int contentsLength = 0;
            int amountRead = -1;
            do {
                int amountRequested = Math.max(stream.available(), DEFAULT_READING_SIZE); // read at least 8K

                // resize contents if needed
                if (contentsLength + amountRequested > contents.length) {
                    System.arraycopy(contents, 0, contents = new byte[contentsLength + amountRequested], 0, contentsLength);
                }

                // read as many bytes as possible
                amountRead = stream.read(contents, contentsLength, amountRequested);

                if (amountRead > 0) {
                    // remember length of contents
                    contentsLength += amountRead;
                }
            } while (amountRead != -1);

            // resize contents if necessary
            if (contentsLength < contents.length) {
                System.arraycopy(contents, 0, contents = new byte[contentsLength], 0, contentsLength);
            }
        } else {
            contents = new byte[length];
            int len = 0;
            int readSize = 0;
            while ((readSize != -1) && (len != length)) {
                // See PR 1FMS89U
                // We record first the read size. In this case len is the actual read size.
                len += readSize;
                readSize = stream.read(contents, len, length - len);
            }
        }

        return contents;
    }
    
    public static void main(String[] args) throws Exception {
        File iniFile = new File(FileUtil.class.getResource("init.sql").toURI());
        
        FileReader reader = new FileReader(iniFile);
        BufferedReader bufferReader = new BufferedReader(reader);
        
        String all = "";
        String row;
        while((row = bufferReader.readLine())!=null){
         if (!row.contains("--")) {
             row = row.replaceAll("\r\n", " ");
             row = row.replaceAll("\r", " ");
             row = row.replaceAll("\n", " ");
//             row = row.replaceAll(";", "\r\n");
             if (row.endsWith(";")) {
                 row = row + " " + "\r\n";
             } else {
                 row = row + " ";
             }
             all = all + row;
         }
        }
        System.out.println(all);
    }

}
 

 

分享到:
评论

相关推荐

    JDBC驱动包(SQLSERVER ORACLE MYSQL HSQL)

    JDBC提供了一种标准的API,使得Java开发者能够连接各种不同类型的数据库系统,包括SQL Server、Oracle、MySQL和HSQL等。 SQL Server是由微软公司开发的一款关系型数据库管理系统,广泛应用于企业级应用,支持多种...

    数据库 jdbc 驱动大全(oracle,sqlserver,sqlserver2005,mysql,hsql) 下载

    数据库JDBC驱动是Java应用程序与各种数据库之间通信的桥梁,它们允许Java代码执行SQL语句并处理返回的结果。本文将详细介绍这些驱动以及如何在不同数据库中使用它们。 首先,Oracle JDBC驱动是Oracle数据库的官方...

    hsql数据转移mysql

    - **导入数据**:有多种方式将数据导入到MySQL,如使用`LOAD DATA INFILE` SQL语句,或者使用MySQL的`mysqlimport`工具,或者编程语言如Java的JDBC API进行批量插入。 - **处理外键和触发器**:如果原HSQLDB数据库...

    hsql-file数据库的java简单调用实现

    标题中的“hsql-file数据库的java简单调用实现”指的是使用Java编程语言与HSQLDB(HyperSQL数据库)进行交互,特别是在文件模式下操作数据库。HSQLDB是一种轻量级、开源的关系型数据库管理系统,它支持内存模式和...

    hsql可视化工具

    HSQL(HyperSQL)是一种轻量级、高性能的关系型数据库管理系统,它支持SQL标准并提供了多种运行模式,包括单用户模式、嵌入式模式和服务器模式。HSQL因其小巧、快速和易于使用而受到开发者们的青睐,尤其适用于开发...

    有关hsql处理文本数据库的笔记

    总结来说,HSQL处理文本数据库的能力使其成为开发人员的有力工具。通过理解如何创建数据库模式,定义表结构,以及利用Java API或脚本导入CSV数据,我们可以轻松地构建和管理文本数据库。这不仅简化了测试环境的设置...

    HSQL源代码

    《深入理解HSQL源代码与Eclipse环境搭建》 HSQLDB,全称为HyperSQL Database,是一款开源的关系型数据库管理系统,特别适用于Java应用程序。它的源代码开放,使得开发者能够深入理解其内部工作原理,进行定制化开发...

    收集的全部HSQL DataBase资料(HSQL DataBase-关于Java 的纯数据库)

    HSQL Database,全称为HyperSQL Database,是一款轻量级、高性能、开源的SQL关系型数据库管理系统,特别适合于Java应用程序。这款数据库系统以其简洁的API、快速的性能和全面的SQL支持,在Java开发环境中得到了广泛...

    基于 Antlr4 的 Hive SQL 解析.zip

    4. **实现解析器**:利用Antlr4生成的解析器类,处理输入的Hive SQL语句,构建并遍历AST,以执行语句的逻辑。 5. **测试和优化**:编写测试用例,确保解析器能够正确处理各种复杂的Hive SQL查询,同时优化性能,...

    报表性能优化方案之单数据集分页SQL实现层式报表

    行式引擎按页取数只适用于Oracle,mysql,hsql和sqlserver2008及以上数据库,其他数据库,如access,sqlserver2005,sqlite等必须编写分页SQL。今天我们以Access数据库为例介绍需要写分页SQL的数据库怎样利用行式的...

    HSQL JDBC操作

    从标签“源码”我们可以推断,这篇博客可能深入解析了HSQLDB与JDBC交互的源代码实现,这将涉及到Java的类库,如`java.sql.Connection`、`java.sql.Statement`、`java.sql.ResultSet`等,以及如何通过这些类来创建...

    jira从HSQL迁移到MYSQL的方法

    ### Jira从HSQL迁移到MYSQL的方法 在IT项目管理和软件开发领域中,Jira作为一款广泛使用的工具,其数据库迁移是一项重要的维护任务。本文将详细介绍如何从HSQL(HyperSQL Database Engine)迁移到MySQL的过程,确保...

    HSQL数据库2.2.5

    HSQL数据库,全称为HyperSQL Database,是一款开源的、轻量级的Java数据库管理系统,尤其适用于内存模式、单机模式以及分布式多机环境。HSQLDB 2.2.5是其一个重要的版本,提供了丰富的功能和优化,使得它在各种应用...

    HSQL安装部署使用手册

    《HSQL数据库安装部署使用详解》 HSQL(HyperSQL)是一种轻量级、高性能的关系型数据库管理系统,常用于开发测试环境或者嵌入式应用。本文将详细介绍HSQL的安装、部署以及使用过程,帮助您顺利搭建并操作HSQL数据库...

    pentaho HSQL连接教程

    5. **多数据库支持**:Pentaho BI Suite不仅支持HSQLDB,还支持多种主流数据库系统,如MySQL、Oracle、SQL Server等。这使得用户可以根据具体需求选择合适的数据库后端。 通过上述步骤,你可以成功地在Pentaho BI ...

    hsql数据库详细教程.pdf

    hsql 数据库的优点是体积小、支持Java 编程、支持SQL99 和SQL2003的大部分标准、可以作为商业应用程序展示的一种选择。缺点是需要手动管理数据库文件,不推荐使用Memory-Only 模式。 hsql 数据库的应用场景包括: ...

    hsql查询语法

    HSQL查询语句对大小写并不敏感,除了Java类和属性名称外。因此,SELECT、SeLeCt、select都是相同的。但是,org.hibernate.eg.FOO并不等于org.hibernate.eg.Foo,同样,foo.barSet也不等于foo.BARSET。 2. FROM子句 ...

Global site tag (gtag.js) - Google Analytics