`
keating
  • 浏览: 169970 次
  • 性别: Icon_minigender_1
  • 来自: weihai
社区版块
存档分类
最新评论

FileOperater

    博客分类:
  • Java
 
阅读更多
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/**
 * 文件操作类
 *
 * @author  keating
 */
public class FileOperater {

    /**
     * 文件复制方法
     * @throws IOException 
     */
    public static void copyFile(File source, File out) throws IOException {
    	FileInputStream inFile = null;
    	FileOutputStream outFile = null;
        try {
            inFile = new FileInputStream(source);
            outFile = new FileOutputStream(out);
            byte[] buffer = new byte[1024];
            int i = 0;
            while ((i = inFile.read(buffer)) != -1) {
                outFile.write(buffer, 0, i);
            }
        } catch (IOException e) {
        	throw e;
        } finally {
			try {
				if (outFile != null)
					outFile.close();
        	}catch(IOException ex) {
        		throw ex;
        	}finally {
        		if(inFile != null)
            		inFile.close();
        	}
        }
    }

    /**
     * 文件打开方法
     * @throws IOException 
     */
    public static void openFile(File file) throws IOException {
		Runtime r = Runtime.getRuntime();
		String name = file.getAbsolutePath().replace(" ", "%20");
		r.exec("cmd /c start " + "file:///" + name);
    }

    /**
     * 得到一个文件的内容,以字符串的形式返回
     * @throws IOException 
     */
    public static String readText(File file) throws IOException {
        StringBuilder content = new StringBuilder();
        BufferedReader reader = null;
        try {
            InputStreamReader pr = new InputStreamReader(new FileInputStream(file), "UTF-8");
            reader = new BufferedReader(pr);
            String temp = null;
            while ((temp = reader.readLine()) != null) {
                content.append(temp);
            }
        } catch (IOException e) {
        	throw e;
        } finally {
        	if(reader != null) {
        		reader.close();
        	}
        }
        return content.toString();
    }

	/**
	 * 将字符串写到一个文件中去,实际上是删除这个文件重新创建,然后写内容
	 * 
	 * @throws IOException
	 */
	public static void writeText(File file, String text) throws IOException {
		OutputStreamWriter pw = null;
		try {
			pw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
			pw.append(text);
		} catch (IOException e) {
			throw e;
		} finally {
			if (pw != null)
				pw.close();
		}
	}
}
分享到:
评论
1 楼 keating 2010-02-07  
Windows xp中文版默认编码应该是gb2312,读取xml文件写入utf-8编码的mysql总是乱码,故读写文件时都采用utft-8编码。

相关推荐

Global site tag (gtag.js) - Google Analytics