FileUtil

package com.sixfacet.framework.web.util.file;

import java.io.BufferedInputStream;
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.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

public class FileUtil {

    public static List<MultipartFile> getFiles(HttpServletRequest request) throws Exception {
        
        MultipartHttpServletRequest req = (MultipartHttpServletRequest)request;
        MultipartFile file = null;
        List<MultipartFile> files = new ArrayList<MultipartFile>();
        for(Object o: req.getFileMap().values()) {
            if(o != null) {
                file = (MultipartFile)o;
                files.add(file);
            }
        }
        return files;
    }
    
    public static void saveXmlToFile(String xml, String fileName) throws IOException{
        FileWriter outFile = new FileWriter(fileName);
        PrintWriter out = new PrintWriter(outFile);
        try {
            out.write(xml);
        } finally {
            out.close();
            outFile.close();
        }
    }
    
    public static String readXmlFromFile(String fileName) throws IOException{
        //create FileInputStream object
        FileInputStream fin = new FileInputStream(fileName);
        
        //create object of BufferedInputStream
        BufferedInputStream bin = new BufferedInputStream(fin);
        
        String strFileContents = "";
        
        try {
            //create a byte array
            byte[] contents = new byte[1024];
            int bytesRead=0;
            while( (bytesRead = bin.read(contents)) != -1){
                strFileContents += new String(contents, 0, bytesRead);
            }
        } finally {
            bin.close();
            fin.close();
        }
        return strFileContents;
    }
    
    public static void copyfile(File srFile, File dtFile) throws IOException{
        InputStream in = new FileInputStream(srFile);

        //For Append the file.
        //OutputStream out = new FileOutputStream(f2,true);

        //For Overwrite the file.
        OutputStream out = new FileOutputStream(dtFile);

        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0){
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }
    
    public static void deletefile(File file) throws IOException{
        // Make sure the file or directory exists and isn't write protected
        if (!file.exists())
          throw new IllegalArgumentException(
              "Delete: no such file or directory: " + file.getName());

        if (!file.canWrite())
          throw new IllegalArgumentException("Delete: write protected: "
              + file.getName());

        // If it is a directory, make sure it is empty
        if (file.isDirectory()) {
          String[] files = file.list();
          if (files.length > 0)
            throw new IllegalArgumentException(
                "Delete: directory not empty: " + file.getName());
        }

        // Attempt to delete it
        boolean success = file.delete();

        if (!success)
          throw new IllegalArgumentException("Delete: deletion failed");
    }
    
    /**
     * Get File Type for a given MultipartFile
     * @param attachedFile
     * @return
     */
    public static String getFileType(MultipartFile attachedFile){
        return getFileType(attachedFile.getOriginalFilename());
    }
    
    /**
     * Get File Type for a given File
     * @param attachedFile
     * @return
     */
    public static String getFileType(File attachedFile){
        return getFileType(attachedFile.getName());
    }
    
    /**
     * Get File Type for a given filename
     * If a file extension is not recognized, application/octet-stream is assumed
     * @param filename
     * @return
     */
    public static String getFileType(String filename){
        if (filename.endsWith(".PDF") || filename.endsWith(".pdf")){
            return "application/pdf";
        } else if (filename.endsWith(".doc") || filename.endsWith(".DOC")){
            return "application/msword";
        } else if (filename.endsWith(".xls") || filename.endsWith(".XLS")){
            return "application/msexcel";
        }else{
            return "application/octet-stream";
        }
        
    }
    
    public static void saveBytesToFile(byte[] fileDate, File file) throws IOException{

        FileOutputStream outFile = new FileOutputStream(file);
        outFile.write(fileDate);
        outFile.close();
    }
    
    public static byte[] getBytesFromFile(File file) throws IOException {
        
        InputStream is = new FileInputStream(file);
    
        // Get the size of the file
        long length = file.length();
    
        if (length > Integer.MAX_VALUE) {
            // File is too large
        }
    
        // Create the byte array to hold the data
        byte[] bytes = new byte[(int)length];
    
        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }
    
        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "+file.getName());
        }
    
        // Close the input stream and return bytes
        is.close();
        return bytes;
    }
}

package com.hexiang.utils; import java.io.*; /** * FileUtil. Simple file operation class. * * @author BeanSoft * */ public class FileUtil { /** * The buffer. */ protected static byte buf[] = new byte[1024]; /** * Read content from local file. FIXME How to judge UTF-8 and GBK, the * correct code should be: FileReader fr = new FileReader(new * InputStreamReader(fileName, "ENCODING")); Might let the user select the * encoding would be a better idea. While reading UTF-8 files, the content * is bad when saved out. * * @param fileName - * local file name to read * @return * @throws Exception */ public static String readFileAsString(String fileName) throws Exception { String content = new String(readFileBinary(fileName)); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(String fileName, String encoding) throws Exception { String content = new String(readFileBinary(fileName), encoding); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(InputStream in) throws Exception { String content = new String(readFileBinary(in)); return content; } /** * Read content from local file to binary byte array. * * @param fileName - * local file name to read * @return * @throws Exception */ public static byte[] readFileBinary(String fileName) throws Exception { FileInputStream fin = new FileInputStream(fileName); return readFileBinary(fin); } /** * 从输入流读取数据为二进制字节数组. * @param streamIn * @return * @throws IOException */ public static byte[] readFileBinary(InputStream streamIn) throws IOException { BufferedInputStream in = new BufferedInputStream(streamIn); ByteArrayOutputStream out = new ByteArrayOutputStream(10240); int len; while ((len
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值