- package org.jr.io;
- /**
- * Copyright: Copyright (c) 2002-2004
- * Company: JavaResearch(http://www.javaresearch.org)
- * 最后更新日期:2004年8月31日
- * @author Cherami
- */
-
- import java.io.*;
- import java.net.MalformedURLException;
- import java.net.URL;
- /**
- * 此类中封装一些常用的读文件操作。
- * 所有方法都是静态方法,不需要生成此类的实例,
- * 为避免生成此类的实例,构造方法被申明为private类型的。
- * @since 0.6
- */
- public class FileReader {
- /**
- * 私有构造方法,防止类的实例化,因为工具类不需要实例化。
- */
- private FileReader() {
- }
- /**
- * 从指定的文件中读取一个序列化的对象。
- * @param filename 文件名
- * @return 序列化文件对应的对象,有任何错误返回null。
- * @since 0.6
- */
- public static Object readObject(String filename) {
- return readObject(new File(filename));
- }
-
- /**
- * 从指定的文件中读取一个序列化的对象。
- * @param file 文件
- * @return 序列化文件对应的对象,有任何错误返回null。
- * @since 0.6
- */
- public static Object readObject(File file) {
- try {
- return readObject(file.toURL());
- }
- catch (MalformedURLException e) {
- e.printStackTrace();
- return null;
- }
- }
-
- /**
- * 从指定的URL中读取一个序列化的对象。
- * @param url 文件位置
- * @return 序列化文件对应的对象,有任何错误返回null。
- * @since 0.6
- */
- public static Object readObject(URL url) {
- ObjectInputStream input=null;
- try {
- input = new ObjectInputStream(url.openStream());
- return input.readObject();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- }finally {
- if (input!=null) {
- try {
- input.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- return null;
- }
-
- /**
- * 读取文件内容并作为一个字符串返回。
- * 文件中的换行符都被删除了。
- * @param file 文件
- * @return 文件内容
- * @since 0.6
- */
- public static String getFileContent(File file) {
- BufferedReader reader = null;
- StringBuffer content = new StringBuffer(1024);
- try {
- reader = new BufferedReader(new java.io.FileReader(file));
- String line = reader.readLine();
- while (line != null) {
- content.append(line);
- line = reader.readLine();
- }
- return content.toString();
- }
- catch (IOException e) {
- System.err.println(e.getMessage());
- return "";
- }
- finally {
- if (reader != null) {
- try {
- reader.close();
- }
- catch (IOException ioe) {
- System.err.println(ioe.getMessage());
- return content.toString();
- }
- }
- }
- }
-
- }