canofy 发表于 2013-2-4 19:51:09

文件读取

package cn.test;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import org.apache.commons.lang.StringUtils;public class FileUtils { public static final String TEMPLATE_PATH= "c:\\FileUtils.java"; public static final String TEMPLATE_OUTPATH= "c:\\out.txt"; public static final String TEMPLATE_INPATH= "cn/test.txt";publicString getFileContent(String path,String charset){StringBuffer sb=new StringBuffer();String line;BufferedReader br=null;try {br=new BufferedReader(new InputStreamReader(new FileInputStream(path),charset));while((line=br.readLine())!=null){sb.append(line);sb.append("\n");}} catch (UnsupportedEncodingException e) {System.out.println("读取文件有误!");//e.printStackTrace();} catch (IOException e) {System.out.println("读取文件有误!");//e.printStackTrace();}finally{if(!StringUtils.isEmpty(br.toString())){try {br.close();} catch (IOException e) {System.out.println("关闭文件有误");e.printStackTrace();}}}return sb.toString();}public String fileReadToString(String path){StringBuffer sb=new StringBuffer();String line;BufferedReader br=null;try {//ClassLoader.getSystemResourceAsStream(path)中的path路径是类路径下的文件//如包cn下有test.txt文件,则路径是"cn/test.txt"。br=new BufferedReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream(path),"UTF-8"));while((line=br.readLine())!=null){sb.append(line);sb.append("\n");}} catch (UnsupportedEncodingException e) {System.out.println("读取文件有误!");//e.printStackTrace();} catch (IOException e) {System.out.println("读取文件有误!");//e.printStackTrace();}finally{if(!StringUtils.isEmpty(br.toString())){try {br.close();} catch (IOException e) {System.out.println("关闭文件有误");e.printStackTrace();}}}return sb.toString();}public void stringWriteToTxt(String str,String path){BufferedWriter bw=null;try {bw=new BufferedWriter(new FileWriter(path));bw.write(str);} catch (IOException e) {System.out.println("写文件时有错误!");e.printStackTrace();}finally{if(bw!=null){try {bw.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}public static void main(String[] args) throws FileNotFoundException{FileUtils fileUtils=new FileUtils();String str=fileUtils.fileReadToString(TEMPLATE_INPATH);System.out.println(str);fileUtils.stringWriteToTxt(str, TEMPLATE_OUTPATH);File file=new File(TEMPLATE_OUTPATH);FileInputStream is=new FileInputStream(file);ClassLoader.getSystemResourceAsStream(TEMPLATE_INPATH);}}
页: [1]
查看完整版本: 文件读取