1. package org.jr.io;
  2. /**
  3. * Copyright: Copyright (c) 2002-2004
  4. * Company: JavaResearch(http://www.javaresearch.org)
  5. * 最后更新日期:2004年8月31日
  6. * @author Cherami
  7. */
  8. import java.io.*;
  9. import java.net.MalformedURLException;
  10. import java.net.URL;
  11. /**
  12. * 此类中封装一些常用的读文件操作。
  13. * 所有方法都是静态方法,不需要生成此类的实例,
  14. * 为避免生成此类的实例,构造方法被申明为private类型的。
  15. * @since 0.6
  16. */
  17. public class FileReader {
  18. /**
  19. * 私有构造方法,防止类的实例化,因为工具类不需要实例化。
  20. */
  21. private FileReader() {
  22. }
  23. /**
  24. * 从指定的文件中读取一个序列化的对象。
  25. * @param filename 文件名
  26. * @return 序列化文件对应的对象,有任何错误返回null。
  27. * @since 0.6
  28. */
  29. public static Object readObject(String filename) {
  30. return readObject(new File(filename));
  31. }
  32. /**
  33. * 从指定的文件中读取一个序列化的对象。
  34. * @param file 文件
  35. * @return 序列化文件对应的对象,有任何错误返回null。
  36. * @since 0.6
  37. */
  38. public static Object readObject(File file) {
  39. try {
  40. return readObject(file.toURL());
  41. }
  42. catch (MalformedURLException e) {
  43. e.printStackTrace();
  44. return null;
  45. }
  46. }
  47. /**
  48. * 从指定的URL中读取一个序列化的对象。
  49. * @param url 文件位置
  50. * @return 序列化文件对应的对象,有任何错误返回null。
  51. * @since 0.6
  52. */
  53. public static Object readObject(URL url) {
  54. ObjectInputStream input=null;
  55. try {
  56. input = new ObjectInputStream(url.openStream());
  57. return input.readObject();
  58. } catch (IOException e) {
  59. e.printStackTrace();
  60. } catch (ClassNotFoundException e) {
  61. e.printStackTrace();
  62. }finally {
  63. if (input!=null) {
  64. try {
  65. input.close();
  66. } catch (IOException e) {
  67. e.printStackTrace();
  68. }
  69. }
  70. }
  71. return null;
  72. }
  73. /**
  74. * 读取文件内容并作为一个字符串返回。
  75. * 文件中的换行符都被删除了。
  76. * @param file 文件
  77. * @return 文件内容
  78. * @since 0.6
  79. */
  80. public static String getFileContent(File file) {
  81. BufferedReader reader = null;
  82. StringBuffer content = new StringBuffer(1024);
  83. try {
  84. reader = new BufferedReader(new java.io.FileReader(file));
  85. String line = reader.readLine();
  86. while (line != null) {
  87. content.append(line);
  88. line = reader.readLine();
  89. }
  90. return content.toString();
  91. }
  92. catch (IOException e) {
  93. System.err.println(e.getMessage());
  94. return "";
  95. }
  96. finally {
  97. if (reader != null) {
  98. try {
  99. reader.close();
  100. }
  101. catch (IOException ioe) {
  102. System.err.println(ioe.getMessage());
  103. return content.toString();
  104. }
  105. }
  106. }
  107. }
  108. }