FileHelper.java 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package com.sec.xinhua.gateway.utils;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileWriter;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.UnsupportedEncodingException;
  8. import org.apache.log4j.Logger;
  9. import com.alibaba.fastjson.JSON;
  10. import com.alibaba.fastjson.JSONObject;
  11. public class FileHelper {
  12. private static final Logger logger = Logger.getLogger(FileHelper.class);
  13. public static String readFile(final File file) {
  14. if (file == null) {
  15. return null;
  16. }
  17. String result = null;
  18. if (file.exists()) {
  19. InputStream in = null;
  20. try {
  21. in = new FileInputStream(file);
  22. result = readFile(in);
  23. } catch (Exception e) {
  24. logger.error("Read file error,the file:" + file.getAbsolutePath(), e);
  25. } finally {
  26. if (in != null) {
  27. try {
  28. in.close();
  29. } catch (IOException e) {
  30. logger.error("Close stream error,the file:" + file.getAbsolutePath());
  31. }
  32. }
  33. }
  34. }
  35. return result;
  36. }
  37. public static String readFile(final InputStream in) throws IOException, UnsupportedEncodingException {
  38. int len = in.available();
  39. byte[] data = new byte[len];
  40. in.read(data, 0, len);
  41. return new String(data, SysConstants.ENCODE);
  42. }
  43. public static void writeFileNotSafe(final String str, final String fileName) throws IOException {
  44. File file = new File(fileName);
  45. File fileParent = file.getParentFile();
  46. if (fileParent != null) {
  47. fileParent.mkdirs();
  48. }
  49. FileWriter fileWriter = null;
  50. try {
  51. fileWriter = new FileWriter(file);
  52. fileWriter.write(str);
  53. } catch (IOException e) {
  54. logger.error("Write file error,the file name:" + fileName);
  55. throw e;
  56. } finally {
  57. if (fileWriter != null) {
  58. try {
  59. fileWriter.close();
  60. } catch (IOException e) {
  61. logger.error("Close file writer error,the file name:" + fileName);
  62. throw e;
  63. }
  64. }
  65. }
  66. }
  67. public static void main(String[] args) {
  68. try {
  69. String s = FileHelper.readFile(new FileInputStream(new File("d:/test.txt")));
  70. System.out.println(s);
  71. JSONObject json = JSON.parseObject(s);
  72. System.out.println(json.getString("a"));
  73. System.out.println(json.getString("b"));
  74. System.out.println(json.getString("c"));
  75. } catch (Exception e) {
  76. e.printStackTrace();
  77. }
  78. }
  79. }