java生成帶二維碼

利用google的zxing jar包生成帶logo或不帶logo的二維碼,相關maven依賴:

<dependency>  
            <groupId>com.google.zxing</groupId>  
            <artifactId>javase</artifactId>  
            <version>3.0.0</version>  
        </dependency>

封裝好的工具類如下:

package com.cbj.util;

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
 * 自定義生成二維碼
 * @author admin
 *
 */
public class QRCodeUtil {
	private static final String CHARSET = "utf-8";  
    private static final String FORMAT_NAME = "PNG";  
    // 二維碼尺寸  
    private static final int QRCODE_SIZE = 200;  
    // LOGO寬度  
    private static final int WIDTH = 60;  
    // LOGO高度  
    private static final int HEIGHT = 60;  
  
    private static BufferedImage createImage(String content, String imgPath,  
            boolean needCompress) throws Exception {  
        return createImage(content,  imgPath,  
                 needCompress,QRCODE_SIZE);  
    }  
    private static BufferedImage createImage(String content, String imgPath,  
            boolean needCompress,int qrcodeSize) throws Exception {  
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();  
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);  
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);  
        hints.put(EncodeHintType.MARGIN, 1);  
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,  
                BarcodeFormat.QR_CODE, qrcodeSize, qrcodeSize, hints);  
        int width = bitMatrix.getWidth();  
        int height = bitMatrix.getHeight();  
        BufferedImage image = new BufferedImage(width, height,  
                BufferedImage.TYPE_INT_RGB);  
        for (int x = 0; x < width; x++) {  
            for (int y = 0; y < height; y++) {  
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000  
                        : 0xFFFFFFFF);  
            }  
        }  
        if (imgPath == null || "".equals(imgPath)) {  
            return image;  
        }  
        // 插入圖片  
        QRCodeUtil.insertImage(image, imgPath, needCompress,qrcodeSize);  
        return image;  
    } 
    /** 
     * 插入LOGO 
     *  
     * @param source 
     *            二維碼圖片 
     * @param imgPath 
     *            LOGO圖片地址 
     * @param needCompress 
     *            是否壓縮 
     * @throws Exception 
     */  
    private static void insertImage(BufferedImage source, String imgPath,  
            boolean needCompress,int qrcodeSize) throws Exception {  
        File file = new File(imgPath);  
        if (!file.exists()) {  
            return;  
        }  
        Image src = ImageIO.read(new File(imgPath));  
        int width = src.getWidth(null);  
        int height = src.getHeight(null);  
        if (needCompress) { // 壓縮LOGO  
            if (width > qrcodeSize/QRCODE_SIZE*WIDTH) {  
                width = qrcodeSize/QRCODE_SIZE*WIDTH;  
            }  
            if (height > qrcodeSize/QRCODE_SIZE*HEIGHT) {  
                height = qrcodeSize/QRCODE_SIZE*HEIGHT;  
            }  
            Image image = src.getScaledInstance(width, height,  
                    Image.SCALE_SMOOTH);  
            BufferedImage tag = new BufferedImage(width, height,  
                    BufferedImage.TYPE_INT_RGB);  
            Graphics g = tag.getGraphics();  
            g.drawImage(image, 0, 0, null); // 繪製縮小後的圖  
            g.dispose();  
            src = image;  
        }  
        // 插入LOGO  
        Graphics2D graph = source.createGraphics();  
        int x = (qrcodeSize - width) / 2;  
        int y = (qrcodeSize - height) / 2;  
        graph.drawImage(src, x, y, width, height, null);  
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);  
        graph.setStroke(new BasicStroke(3f));  
        graph.draw(shape);  
        graph.dispose();  
    }  
  
    /** 
     * 生成二維碼(內嵌LOGO) 
     *  
     * @param content 
     *            內容 
     * @param imgPath 
     *            LOGO地址 
     * @param destPath 
     *            存儲地址 
     * @param needCompress 
     *            是否壓縮LOGO 
     * @throws Exception 
     */  
    public static void encode(String content, String imgPath, String destPath,  
            boolean needCompress) throws Exception {  
        BufferedImage image = QRCodeUtil.createImage(content, imgPath,  
                needCompress);  
    //    FileUtils.mkdirs(destPath);  
        FileUtils.mkdir(destPath, false);
        ImageIO.write(image, FORMAT_NAME, new File(destPath));  
    }  
    /**
     * 
     * @author eason	
     * @param content   內容
     * @param imgPath   LOGO地址 
     * @param destPath  存儲地址
     * @param needCompress 是否壓縮LOGO
     * @param qrcodeSize 二維碼大小 寬高
     * @throws Exception
     */
    public static void encode(String content, String imgPath, String destPath,  
            boolean needCompress,int qrcodeSize) throws Exception {  
        BufferedImage image = QRCodeUtil.createImage(content, imgPath,  
                needCompress,qrcodeSize);  
        FileUtils.mkdir(destPath, false);
        ImageIO.write(image, FORMAT_NAME, new File(destPath));  
    }  
  
  
    /** 
     * 生成二維碼(內嵌LOGO) 
     *  
     * @param content 
     *            內容 
     * @param imgPath 
     *            LOGO地址 
     * @param destPath 
     *            存儲地址 
     * @throws Exception 
     */  
    public static void encode(String content, String imgPath, String destPath)  
            throws Exception {  
        QRCodeUtil.encode(content, imgPath, destPath, false);  
    }  
    public static void encode(String content, String imgPath, String destPath,int qrcodeSize)  
            throws Exception {  
        QRCodeUtil.encode(content, imgPath, destPath, false);  
    } 
    /** 
     * 生成二維碼 
     *  
     * @param content 
     *            內容 
     * @param destPath 
     *            存儲地址 
     * @param needCompress 
     *            是否壓縮LOGO 
     * @throws Exception 
     */  
    public static void encode(String content, String destPath,  
            boolean needCompress) throws Exception {  
        QRCodeUtil.encode(content, null, destPath, needCompress);  
    }  
  
    /** 
     * 生成二維碼 
     *  
     * @param content 
     *            內容 
     * @param destPath 
     *            存儲地址 
     * @throws Exception 
     */  
    public static void encode(String content, String destPath) throws Exception {  
        QRCodeUtil.encode(content, null, destPath, false);  
    }  
  
    /** 
     * 生成二維碼(內嵌LOGO) 
     *  
     * @param content 
     *            內容 
     * @param imgPath 
     *            LOGO地址 
     * @param output 
     *            輸出流 
     * @param needCompress 
     *            是否壓縮LOGO 
     * @throws Exception 
     */  
    public static void encode(String content, String imgPath,  
            OutputStream output, boolean needCompress) throws Exception {  
        BufferedImage image = QRCodeUtil.createImage(content, imgPath,  
                needCompress);  
        ImageIO.write(image, FORMAT_NAME, output);  
    }  
    /**
     * 
     * @author eason	
     * @param content  內容 
     * @param imgPath  LOGO地址 
     * @param output 輸出流
     * @param needCompress  是否壓縮LOGO 
     * @param qrcodeSize
     * @throws Exception
     */
    public static void encode(String content, String imgPath,  
            OutputStream output, boolean needCompress,int qrcodeSize) throws Exception {  
        BufferedImage image = QRCodeUtil.createImage(content, imgPath,  
                needCompress,qrcodeSize); 
        ImageIO.write(image, FORMAT_NAME, output);  
    }  
    public static void encode(String content, OutputStream output,int qrcodeSize)  
            throws Exception {  
        QRCodeUtil.encode(content, null, output, false,qrcodeSize);  
    }  
    /** 
     * 生成二維碼 
     *  
     * @param content 
     *            內容 
     * @param output 
     *            輸出流 
     * @throws Exception 
     */  
    public static void encode(String content, OutputStream output)  
            throws Exception {  
        QRCodeUtil.encode(content, null, output, false);  
    }  
  
    /** 
     * 解析二維碼 
     *  
     * @param file 
     *            二維碼圖片 
     * @return 
     * @throws Exception 
     */  
    public static String decode(File file) throws Exception {  
        BufferedImage image;  
        image = ImageIO.read(file);  
        if (image == null) {  
            return null;  
        }  
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(  
                image);  
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));  
        Result result;  
        Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();  
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);  
        result = new MultiFormatReader().decode(bitmap, hints);  
        String resultStr = result.getText();  
        return resultStr;  
    }  
  
    /** 
     * 解析二維碼 
     *  
     * @param path 
     *            二維碼圖片地址 
     * @return 
     * @throws Exception 
     */  
    public static String decode(String path) throws Exception {  
        return QRCodeUtil.decode(new File(path));  
    }  
  
    public static void main(String[] args) throws Exception {  
        String text = "{\"partId\":234}";  
        QRCodeUtil.encode(text, "/Users/yulong/git/myutils/logo_180x180.png", "/Users/yulong/git/myutils/logo3.png", false,600);  
    }  
}

FileUtils類:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import javax.swing.filechooser.FileFilter;

/**
 * 此類中封裝一些常用的文件操作。
 * 所有方法都是靜態方法,不需要生成此類的實例,
 * 爲避免生成此類的實例,構造方法被申明爲private類型的。
 * @since  0.1
 */

public class FileUtils
{
    /**
     * 私有構造方法,防止類的實例化,因爲工具類不需要實例化。
     */
    private FileUtils()
    {

    }
    /**
	 * 根據需要創建文件夾
	 * 
	 * @param dirPath
	 *            文件夾路徑
	 * @param del
	 *            存在文件夾是否刪除
	 */
	public static void mkdir(String dirPath, boolean del) {
		File dir = new File(dirPath);
		if (dir.exists()) {
			if (del)
				dir.delete();
			else
				return;
		}
		if (!dir.getParentFile().exists()) {
			dir.getParentFile().mkdirs();
		}
	}

 
    public static boolean expiredFile(Long modifiedTimeMS,int minutes) {
    	long maxMillis=modifiedTimeMS + minutes*60*1000;
    	long nowMillis=System.currentTimeMillis();
		return maxMillis< nowMillis; 
	}
   
    /**
     * 修改文件的最後訪問時間。
     * 如果文件不存在則創建該文件。
     * <b>目前這個方法的行爲方式還不穩定,主要是方法有些信息輸出,這些信息輸出是否保留還在考慮中。</b>
     * @param file 需要修改最後訪問時間的文件。
     * @since  0.1
     */
    public static void touch(File file)
    {
        long currentTime = System.currentTimeMillis();
        if (!file.exists())
        {
            try
            {
            	if (!file.getParentFile().exists()) {
            		file.getParentFile().mkdirs();
        		}
            }
            catch (Exception e)
            {
                System.err.println("Create file failed!");
                e.printStackTrace();
            }
        }
        boolean result = file.setLastModified(currentTime);
        if (!result)
        {
            System.err.println("touch failed: " + file.getName());
        }
    }

    /**
     * 修改文件的最後訪問時間。
     * 如果文件不存在則創建該文件。
     * <b>目前這個方法的行爲方式還不穩定,主要是方法有些信息輸出,這些信息輸出是否保留還在考慮中。</b>
     * @param fileName 需要修改最後訪問時間的文件的文件名。
     * @since  0.1
     */
    public static void touch(String fileName)
    {
        File file = new File(fileName);
        touch(file);
    }

    /**
     * 修改文件的最後訪問時間。
     * 如果文件不存在則創建該文件。
     * <b>目前這個方法的行爲方式還不穩定,主要是方法有些信息輸出,這些信息輸出是否保留還在考慮中。</b>
     * @param files 需要修改最後訪問時間的文件數組。
     * @since  0.1
     */
    public static void touch(File[] files)
    {
        for (int i = 0; i < files.length; i++)
        {
            touch(files[i]);
        }
    }

    /**
     * 修改文件的最後訪問時間。
     * 如果文件不存在則創建該文件。
     * <b>目前這個方法的行爲方式還不穩定,主要是方法有些信息輸出,這些信息輸出是否保留還在考慮中。</b>
     * @param fileNames 需要修改最後訪問時間的文件名數組。
     * @since  0.1
     */
    public static void touch(String[] fileNames)
    {
        File[] files = new File[fileNames.length];
        for (int i = 0; i < fileNames.length; i++)
        {
            files[i] = new File(fileNames[i]);
        }
        touch(files);
    }

    /**
     * 判斷指定的文件是否存在。
     * @param fileName 要判斷的文件的文件名
     * @return 存在時返回true,否則返回false。
     * @since  0.1
     */
    public static boolean isFileExist(String fileName)
    {
    	
        return new File(fileName).exists();
    }

    /**
     * 創建指定的目錄。
     * 如果指定的目錄的父目錄不存在則創建其目錄書上所有需要的父目錄。
     * <b>注意:可能會在返回false的時候創建部分父目錄。</b>
     * @param file 要創建的目錄
     * @return 完全創建成功時返回true,否則返回false。
     * @since  0.1
     */
    public static boolean makeDirectory(File file)
    {
        //File parent = file.getParentFile();
        //if (parent != null) 
        //{
        return file.mkdirs();
        //}
        //return false;
    }

    /**
     * 創建指定的目錄。
     * 如果指定的目錄的父目錄不存在則創建其目錄書上所有需要的父目錄。
     * <b>注意:可能會在返回false的時候創建部分父目錄。</b>
     * @param fileName 要創建的目錄的目錄名
     * @return 完全創建成功時返回true,否則返回false。
     * @since  0.1
     */
    public static boolean makeDirectory(String fileName)
    {
        boolean bTmp = false;
        try
        {
            File file = new File(fileName.toString());
            makeDirectory(file);
            bTmp = true;
        }
        catch (Exception ex)
        {
            bTmp = false;
            System.out.println(ex.toString());
        }
        return bTmp;
    }

    /**
     * 清空指定目錄中的文件。
     * 這個方法將儘可能刪除所有的文件,但是只要有一個文件沒有被刪除都會返回false。
     * 另外這個方法不會迭代刪除,即不會刪除子目錄及其內容。
     * @param directory 要清空的目錄
     * @return 目錄下的所有文件都被成功刪除時返回true,否則返回false.
     * @since  0.1
     */
    public static boolean emptyDirectory(File directory)
    {
        boolean result = false;
        File[] entries = directory.listFiles();
        for (int i = 0; i < entries.length; i++)
        {
            if (!entries[i].delete())
            {
                result = false;
            }
        }
        return result;
    }

    /**
     * 清空指定目錄中的文件。
     * 這個方法將儘可能刪除所有的文件,但是只要有一個文件沒有被刪除都會返回false。
     * 另外這個方法不會迭代刪除,即不會刪除子目錄及其內容。
     * @param directoryName 要清空的目錄的目錄名
     * @return 目錄下的所有文件都被成功刪除時返回true,否則返回false。
     * @since  0.1
     */
    public static boolean emptyDirectory(String directoryName)
    {
        File dir = new File(directoryName);
        return emptyDirectory(dir);
    }

    /**
     * 刪除指定目錄及其中的所有內容。
     * @param dirName 要刪除的目錄的目錄名
     * @return 刪除成功時返回true,否則返回false。
     * @since  0.1
     */
    public static boolean deleteDirectory(String dirName)
    {
        return deleteDirectory(new File(dirName));
    }

    /**
     * 刪除指定目錄及其中的所有內容。
     * @param dir 要刪除的目錄
     * @return 刪除成功時返回true,否則返回false。
     * @since  0.1
     */
    public static boolean deleteDirectory(File dir)
    {
        if ((dir == null) || !dir.isDirectory()) { throw new IllegalArgumentException("Argument "
                + dir + " is not a directory. "); }

        File[] entries = dir.listFiles();
        int sz = entries.length;

        for (int i = 0; i < sz; i++)
        {
            if (entries[i].isDirectory())
            {
                if (!deleteDirectory(entries[i])) { return false; }
            }
            else
            {
                if (!entries[i].delete()) { return false; }
            }
        }

        if (!dir.delete()) { return false; }
        return true;
    }

    /**
     * 列出目錄中的所有內容,包括其子目錄中的內容。
     * @param fileName 要列出的目錄的目錄名
     * @return 目錄內容的文件數組。
     * @since  0.1
     */
    public static File[] listAll(String fileName)
    {
        return listAll(new File(fileName));
    }

    /**
     * 列出目錄中的所有內容,包括其子目錄中的內容。
     * @param file 要列出的目錄
     * @return 目錄內容的文件數組。
     * @since  0.1
     */
    public static File[] listAll(File file)
    {
        ArrayList<File> list = new ArrayList<File>();
        File[] files;
        if (!file.exists() || file.isFile()) { return null; }
        list(list, file,  new FileFilter() {
            public boolean accept(File file) {
                //if the file extension is .txt return true, else false
            	  return true;
            }
			@Override
			public String getDescription() {
				// TODO Auto-generated method stub
				return null;
			}
        });
        list.remove(file);
        files = new File[list.size()];
        list.toArray(files);
        return files;
    }

    /**
     * 列出目錄中的所有內容,包括其子目錄中的內容。
     * @param file 要列出的目錄
     * @param filter 過濾器
     * @return 目錄內容的文件數組。
     * @since  0.1
     */
    public static File[] listAll(File file,
            javax.swing.filechooser.FileFilter filter)
    {
        ArrayList<File> list = new ArrayList<File>();
        File[] files;
        if (!file.exists() || file.isFile()) { return null; }
        list(list, file, filter);
        files = new File[list.size()];
        list.toArray(files);
        return files;
    }

    /**
     * 將目錄中的內容添加到列表。
     * @param list 文件列表
     * @param filter 過濾器
     * @param file 目錄
     */
    private static void list(ArrayList<File> list, File file,
            javax.swing.filechooser.FileFilter filter)
    {
        if (filter.accept(file))
        {
            list.add(file);
            if (file.isFile()) { return; }
        }
        if (file.isDirectory())
        {
            File files[] = file.listFiles();
            for (int i = 0; i < files.length; i++)
            {
                list(list, files[i], filter);
            }
        }

    }

    /**
     * 返回文件的URL地址。
     * @param file 文件
     * @return 文件對應的的URL地址
     * @throws MalformedURLException
     * @since  0.4
     * @deprecated 在實現的時候沒有注意到File類本身帶一個toURL方法將文件路徑轉換爲URL。
     *             請使用File.toURL方法。
     */
    public static URL getURL(File file) throws MalformedURLException
    {
        String fileURL = "file:/" + file.getAbsolutePath();
        URL url = new URL(fileURL);
        return url;
    }

    /**
     * 從文件路徑得到文件名。
     * @param filePath 文件的路徑,可以是相對路徑也可以是絕對路徑
     * @return 對應的文件名
     * @since  0.4
     */
    public static String getFileName(String filePath)
    {
        File file = new File(filePath);
        return file.getName();
    }

    /**
     * 從文件名得到文件絕對路徑。
     * @param fileName 文件名
     * @return 對應的文件路徑
     * @since  0.4
     */
    public static String getFilePath(String fileName)
    {
        File file = new File(fileName);
        return file.getAbsolutePath();
    }

    /**
     * 將DOS/Windows格式的路徑轉換爲UNIX/Linux格式的路徑。
     * 其實就是將路徑中的"\"全部換爲"/",因爲在某些情況下我們轉換爲這種方式比較方便,
     * 某中程度上說"/"比"\"更適合作爲路徑分隔符,而且DOS/Windows也將它當作路徑分隔符。
     * @param filePath 轉換前的路徑
     * @return 轉換後的路徑
     * @since  0.4
     */
    public static String toUNIXpath(String filePath)
    {
        return filePath.replace('\\', '/');
    }

    /**
     * 從文件名得到UNIX風格的文件絕對路徑。
     * @param fileName 文件名
     * @return 對應的UNIX風格的文件路徑
     * @since  0.4
     * @see #toUNIXpath(String filePath) toUNIXpath
     */
    public static String getUNIXfilePath(String fileName)
    {
        File file = new File(fileName);
        return toUNIXpath(file.getAbsolutePath());
    }

    /**
     * 得到文件的類型。
     * 實際上就是得到文件名中最後一個“.”後面的部分。
     * @param fileName 文件名
     * @return 文件名中的類型部分
     * @since  0.5
     */
    public static String getTypePart(String fileName)
    {
        int point = fileName.lastIndexOf('.');
        int length = fileName.length();
        if (point == -1 || point == length - 1)
        {
            return "";
        }
        else
        {
            return fileName.substring(point + 1, length);
        }
    }

    /**
     * 得到文件的類型。
     * 實際上就是得到文件名中最後一個“.”後面的部分。
     * @param file 文件
     * @return 文件名中的類型部分
     * @since  0.5
     */
    public static String getFileType(File file)
    {
        return getTypePart(file.getName());
    }

    /**
     * 得到文件的名字部分。
     * 實際上就是路徑中的最後一個路徑分隔符後的部分。
     * @param fileName 文件名
     * @return 文件名中的名字部分
     * @since  0.5
     */
    public static String getNamePart(String fileName)
    {
        int point = getPathLastIndex(fileName);
        int length = fileName.length();
        if (point == -1)
        {
            return fileName;
        }
        else if (point == length - 1)
        {
            int secondPoint = getPathLastIndex(fileName, point - 1);
            if (secondPoint == -1)
            {
                if (length == 1)
                {
                    return fileName;
                }
                else
                {
                    return fileName.substring(0, point);
                }
            }
            else
            {
                return fileName.substring(secondPoint + 1, point);
            }
        }
        else
        {
            return fileName.substring(point + 1);
        }
    }

    /**
     * 得到文件名中的父路徑部分。
     * 對兩種路徑分隔符都有效。
     * 不存在時返回""。
     * 如果文件名是以路徑分隔符結尾的則不考慮該分隔符,例如"/path/"返回""。
     * @param fileName 文件名
     * @return 父路徑,不存在或者已經是父目錄時返回""
     * @since  0.5
     */
    public static String getPathPart(String fileName)
    {
        int point = getPathLastIndex(fileName);
        int length = fileName.length();
        if (point == -1)
        {
            return "";
        }
        else if (point == length - 1)
        {
            int secondPoint = getPathLastIndex(fileName, point - 1);
            if (secondPoint == -1)
            {
                return "";
            }
            else
            {
                return fileName.substring(0, secondPoint);
            }
        }
        else
        {
            return fileName.substring(0, point);
        }
    }

    /**
     * 得到路徑分隔符在文件路徑中首次出現的位置。
     * 對於DOS或者UNIX風格的分隔符都可以。
     * @param fileName 文件路徑
     * @return 路徑分隔符在路徑中首次出現的位置,沒有出現時返回-1。
     * @since  0.5
     */
    public static int getPathIndex(String fileName)
    {
        int point = fileName.indexOf('/');
        if (point == -1)
        {
            point = fileName.indexOf('\\');
        }
        return point;
    }

    /**
     * 得到路徑分隔符在文件路徑中指定位置後首次出現的位置。
     * 對於DOS或者UNIX風格的分隔符都可以。
     * @param fileName 文件路徑
     * @param fromIndex 開始查找的位置
     * @return 路徑分隔符在路徑中指定位置後首次出現的位置,沒有出現時返回-1。
     * @since  0.5
     */
    public static int getPathIndex(String fileName, int fromIndex)
    {
        int point = fileName.indexOf('/', fromIndex);
        if (point == -1)
        {
            point = fileName.indexOf('\\', fromIndex);
        }
        return point;
    }

    /**
     * 得到路徑分隔符在文件路徑中最後出現的位置。
     * 對於DOS或者UNIX風格的分隔符都可以。
     * @param fileName 文件路徑
     * @return 路徑分隔符在路徑中最後出現的位置,沒有出現時返回-1。
     * @since  0.5
     */
    public static int getPathLastIndex(String fileName)
    {
        int point = fileName.lastIndexOf('/');
        if (point == -1)
        {
            point = fileName.lastIndexOf('\\');
        }
        return point;
    }

    /**
     * 得到路徑分隔符在文件路徑中指定位置前最後出現的位置。
     * 對於DOS或者UNIX風格的分隔符都可以。
     * @param fileName 文件路徑
     * @param fromIndex 開始查找的位置
     * @return 路徑分隔符在路徑中指定位置前最後出現的位置,沒有出現時返回-1。
     * @since  0.5
     */
    public static int getPathLastIndex(String fileName, int fromIndex)
    {
        int point = fileName.lastIndexOf('/', fromIndex);
        if (point == -1)
        {
            point = fileName.lastIndexOf('\\', fromIndex);
        }
        return point;
    }

    /**
     * 將文件名中的類型部分去掉。
     * @param filename 文件名
     * @return 去掉類型部分的結果
     * @since  0.5
     */
    public static String trimType(String filename)
    {
        int index = filename.lastIndexOf(".");
        if (index != -1)
        {
            return filename.substring(0, index);
        }
        else
        {
            return filename;
        }
    }

    /**
     * 得到相對路徑。
     * 文件名不是目錄名的子節點時返回文件名。
     * @param pathName 目錄名
     * @param fileName 文件名
     * @return 得到文件名相對於目錄名的相對路徑,目錄下不存在該文件時返回文件名
     * @since  0.5
     */
    public static String getSubpath(String pathName, String fileName)
    {
        int index = fileName.indexOf(pathName);
        if (index != -1)
        {
            return fileName.substring(index + pathName.length() + 1);
        }
        else
        {
            return fileName;
        }
    }

    /**
     * 拷貝文件。
     * @param fromFileName 源文件名
     * @param toFileName 目標文件名
     * @return 成功生成文件時返回true,否則返回false
     * @since  0.6
     */
    public static boolean copy(String fromFileName, String toFileName)
    {
        return copy(fromFileName, toFileName, false);
    }

    /**
     * 拷貝文件。
     * @param fromFileName 源文件名
     * @param toFileName 目標文件名
     * @param override 目標文件存在時是否覆蓋
     * @return 成功生成文件時返回true,否則返回false
     * @since  0.6
     */
    public static boolean copy(String fromFileName, String toFileName,
            boolean override)
    {
        File fromFile = new File(fromFileName);
        File toFile = new File(toFileName);

        if (!fromFile.exists() || !fromFile.isFile() || !fromFile.canRead()) { return false; }

        if (toFile.isDirectory())
        {
            toFile = new File(toFile, fromFile.getName());

        }
        if (toFile.exists())
        {
            if (!toFile.canWrite() || override == false) { return false; }
        }
        else
        {
            String parent = toFile.getParent();
            if (parent == null)
            {
                parent = System.getProperty("user.dir");
            }
            File dir = new File(parent);
            if (!dir.exists() || dir.isFile() || !dir.canWrite()) { return false; }
        }

        FileInputStream from = null;
        FileOutputStream to = null;
        try
        {
            from = new FileInputStream(fromFile);
            to = new FileOutputStream(toFile);
            byte[] buffer = new byte[4096];
            int bytes_read;
            while ((bytes_read = from.read(buffer)) != -1)
            {
                to.write(buffer, 0, bytes_read);
            }
            return true;
        }
        catch (IOException e)
        {
            return false;
        }
        finally
        {
            if (from != null)
            {
                try
                {
                    from.close();
                }
                catch (IOException e)
                {
                    ;
                }
            }
            if (to != null)
            {
                try
                {
                    to.close();
                }
                catch (IOException e)
                {
                    ;
                }
            }
        }
    }
    public static String getExtensionName(String filename) {
		return filename.substring(filename.lastIndexOf('.'));
	}
    	/**
    	 * 文件複製
    	 * @author yulong
    	 * @description
    	 * @date 2012-8-29 
    	 * @param src
    	 * @param dst
    	 * @param BUFFER_SIZE
    	 * @return
    	 */
 		public static boolean copy(File src, File dst, int BUFFER_SIZE) {
 			boolean result = false;
 			InputStream in = null;
 			OutputStream out = null;
 			try {
 				in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
 				out = new BufferedOutputStream(new FileOutputStream(dst),
 						BUFFER_SIZE);
 				byte[] buffer = new byte[BUFFER_SIZE];
 				int len = 0;
 				while ((len = in.read(buffer)) > 0) {
 					out.write(buffer, 0, len);
 				}
 				result = true;
 			} catch (Exception e) {
 				e.printStackTrace();
 				result = false;
 			} finally {
 				if (null != in) {
 					try {
 						in.close();
 					} catch (IOException e) {
 						e.printStackTrace();
 					}
 				}
 				if (null != out) {
 					try {
 						out.close();
 					} catch (IOException e) {
 						e.printStackTrace();
 					}
 				}
 			}
 			return result;
 		}
 		public static String getFileContents(File file) {
 			 StringBuilder result = new StringBuilder();
 	        try{
 	            BufferedReader br = new BufferedReader(new FileReader(file));//構造一個BufferedReader類來讀取文件
 	            String s = null;
 	            while((s = br.readLine())!=null){//使用readLine方法,一次讀一行
 	                result.append(s).append("\n");
 	            }
 	            br.close();    
 	        }catch(Exception e){
 	            e.printStackTrace();
 	        }
 	        return result.toString();
 		}
 		
 		public static boolean copy(InputStream in, File dst, int BUFFER_SIZE) {
 			boolean result = false;
 			OutputStream out = null;
 			try {
 				out = new BufferedOutputStream(new FileOutputStream(dst),
 						BUFFER_SIZE);
 				byte[] buffer = new byte[BUFFER_SIZE];
 				int len = 0;
 				while ((len = in.read(buffer)) > 0) {
 					out.write(buffer, 0, len);
 				}
 				result = true;
 			} catch (Exception e) {
 				e.printStackTrace();
 				result = false;
 			} finally {
 				if (null != in) {
 					try {
 						in.close();
 					} catch (IOException e) {
 						e.printStackTrace();
 					}
 				}
 				if (null != out) {
 					try {
 						out.close();
 					} catch (IOException e) {
 						e.printStackTrace();
 					}
 				}
 			}
 			return result;
 		}
    /** 
     * 寫文件到本地 
     * @param in 
     * @param fileName 
     * @throws IOException 
     */  
    public static void copyFile(InputStream in,String fileName,String basePath) throws IOException{
    	FileUtils.mkdir(basePath  
                  + fileName, true);
        FileOutputStream fs = new FileOutputStream(basePath  
                  + fileName);  
          byte[] buffer = new byte[1024 * 1024]; 
          int byteread = 0;  
          while ((byteread = in.read(buffer)) != -1) {  
              fs.write(buffer, 0, byteread);  
              fs.flush();  
          }  
          fs.close();  
          in.close();  
    }  
    // 建立文件夾
 	public void createFold(String path) {
 		try {
 			File folder = new File(path);
 			if (!folder.exists()) {
 				folder.mkdirs();
 			}
 		} catch (Exception e) {
 			e.printStackTrace();
 		}
 	}
    /**
     * 獲得某個文件的絕對路徑
     * @param x
     * @return
     */
    public static String getPath(String x)
    {
        String path = "";
        try
        {
            File file = new File(".");
            path = file.getCanonicalPath() + "\\" + x + "\\";
        }
        catch (IOException e)
        {
            System.out.println("com.job5156.util.FileUtil getPath()  error :"
                    + e.getMessage());
        }
        return path;
    }
    
    public static boolean existFile(String flePath){
    
		return existFile(new File(flePath));		
    }
    
    public static boolean existFile(File file){
    	if(file == null)
    		return false;
    	try {
			return file.exists();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
    }

    /**
     * 獲得路徑
     * @return  根目錄,java/jsp應用程序的根目錄
     * @author Lzj.Liu
     */
    public static String getPath()
    {
        String path = "";
        File file = new File(".");
        try
        {
            path = file.getCanonicalPath();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return path;
    }

    /**
     * 創建資料夾(測試通過)
     * @param folderName 文件夾名稱
     * @return boolean true:ok;false:faild
     */
    public static boolean createFolder(String folderName)
    {
        boolean bTmp = false;
        try
        {
            folderName = folderName.toString();
            File file = new File(folderName);
            if(!file.exists()){
	            file.mkdirs();
            }
            bTmp = true;
        }
        catch (Exception ex)
        {
            System.out.println(ex.toString());
            bTmp = false;
        }
        return bTmp;
    }

    /**
     * 刪除指定的文件
     * @param fileName 指定的文件路徑及文件名
     * @return boolean true:成功;false:失敗
     */
    public static boolean deleteFile(String fileName)
    {
        boolean bTmp = false;
        try
        {
            fileName = fileName.toString();
            File file = new File(fileName);
            if (file.exists())
            {
                file.delete();
                bTmp = true;
            }
            else
            {
                System.out.println(fileName + "文件路徑有誤!");
                bTmp = false;
            }
        }
        catch (Exception ex)
        {
            bTmp = false;
            System.out.println("FileUtil->deleteFile" + ex.toString());
        }
        return bTmp;
    }

    /**
     * 創建指定的文件
     * @param fileName 文件路徑及文件名(如:c:\\a.txt);
     * @return boolean true:成功;false:失敗
     */
    public static boolean createFile(String filePath)
    {
        boolean bTmp = false;
        filePath = filePath.toString();
        File myFilePath = new File(filePath);
        FileWriter resultFile = null;
        try
        {
            if (!myFilePath.exists()) myFilePath.createNewFile();
            resultFile = new FileWriter(myFilePath);
            /*PrintWriter myFile = */new PrintWriter(resultFile);
        }
        catch (Exception ex)
        {
            System.out.println(ex.toString());
        }
        finally
        {
            try
            {
                resultFile.close();
            }
            catch (IOException ioe)
            {
                System.out.println(ioe.toString());
            }
        }
        return bTmp;
    }


    /**
     * 獲得路徑
     * @return 根目錄
     */
    public static String getRootPath()
    {
        return getPath();
    }

    public static void main(String[] args)
    {
        //boolean b=createFolder("uploadpic\\2002515\\xxx.gif");
        //System.out.println(b);
        //boolean bTmp=isFileExist("WEB-INF\\src\\com\\job5156\\util\\FileUtil.java");
        //System.out.println(bTmp);
        //System.out.println(getPath());
        //makeDirectory("uploadpic\\200515\\xxxzzz.gif");
        //deleteDirectory("uploadpic\\200515\\xxxzzz.gif");
        //copy("uploadpic\\123.gif","uploadpic\\xxxyy.gif\\xxx.gif",true);
        //emptyDirectory("uploadpic\\200515");
        System.out.println("---:"+FileUtils.getFileContents(new File("/Users/yulong/git/myutils/src/main/java/com/yulon/util/DesUtil.java")));
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章