file helper

这几天读写文件的操作比较多,就写个帮助类,把打开关闭文件的代码拿出来,现在常用的是 BufferedReader 和 PrintWriter,以后用别的时再加。


import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

public class FileHelper {
/**
* 读文件时的打开文件
*
* @param path
*            要打开的文件路径
* @param charset
*            要以什么字符集打开文件
* @return 返回BufferedReader
*/

public static BufferedReader openFileForRead(
String path, String charset)
throws Exception {
  if (path == null || path.equals(
""))
return null;
  BufferedReader reader = null;
  try {
    if (charset != null && !charset.equals(
""))
        reader = new BufferedReader(
new InputStreamReader(
    new FileInputStream(path), charset));
    else
        reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(path)));
  } catch (Exception e) {
e.printStackTrace();
throw e;
  }
  return reader;
}

public static void closeFileForRead(
Object reader) {
  if (reader == null)
return;
  if (reader instanceof BufferedReader) {
BufferedReader br =
(BufferedReader) reader;
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
  }
}

/**
* 写文件时的打开文件
*
* @param path
*            要写的文件路径
* @param charset
*            要以什么字符集写入文件
* @param append
*            是否追加
* @return PrintWriter
*/

public static PrintWriter openFileForWrite(
String path, String charset,
boolean append) throws Exception {
  if (path == null || path.equals(
""))
return null;
  PrintWriter writer = null;
  try {
    if (charset == null || charset.equals(
"")) {
writer = new PrintWriter(
       new OutputStreamWriter(
       new FileOutputStream(path, append)));
    } else {
writer = new PrintWriter(
   new OutputStreamWriter(
   new FileOutputStream(path, append)
   ,
"UTF-8"));
    }
  } catch (Exception e) {
e.printStackTrace();
throw e;
  }

  return writer;
}

public static void closeFileForWrite(
Object writer){
  if(writer == null)
return;
  if(writer instanceof PrintWriter){
PrintWriter pw = (PrintWriter)writer;
try {
pw.close();
} catch (Exception e) {
e.printStackTrace();
}
  }
}

public static void main(String[] args) {
  try {
    PrintWriter pw = openFileForWrite(
        
"d:/info2.txt", "UTF-8", true);
    pw.println(
"啊");
    closeFileForWrite(pw);

    BufferedReader br = openFileForRead(
        
"d:/info2.txt", "UTF-8");
    echo(br.readLine());
    echo(br.readLine());
    closeFileForRead(br);
  } catch (Exception e) {
e.printStackTrace();
  }
}

public static void echo(String str) {
System.out.println(str);
}

}
irini   2007-03-13 15:27:05 评论:0   阅读:37   引用:0

发表评论>>

署名发表(评论可管理,不必输入下面的姓名)

姓名:

主题:

内容: 最少15个,最长1000个字符

验证码: (如不清楚,请刷新)

Copyright@2008 powered by YuLog