package com.sec.xinhua.gateway.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import org.apache.log4j.Logger; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; public class FileHelper { private static final Logger logger = Logger.getLogger(FileHelper.class); public static String readFile(final File file) { if (file == null) { return null; } String result = null; if (file.exists()) { InputStream in = null; try { in = new FileInputStream(file); result = readFile(in); } catch (Exception e) { logger.error("Read file error,the file:" + file.getAbsolutePath(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.error("Close stream error,the file:" + file.getAbsolutePath()); } } } } return result; } public static String readFile(final InputStream in) throws IOException, UnsupportedEncodingException { int len = in.available(); byte[] data = new byte[len]; in.read(data, 0, len); return new String(data, SysConstants.ENCODE); } public static void writeFileNotSafe(final String str, final String fileName) throws IOException { File file = new File(fileName); File fileParent = file.getParentFile(); if (fileParent != null) { fileParent.mkdirs(); } FileWriter fileWriter = null; try { fileWriter = new FileWriter(file); fileWriter.write(str); } catch (IOException e) { logger.error("Write file error,the file name:" + fileName); throw e; } finally { if (fileWriter != null) { try { fileWriter.close(); } catch (IOException e) { logger.error("Close file writer error,the file name:" + fileName); throw e; } } } } public static void main(String[] args) { try { String s = FileHelper.readFile(new FileInputStream(new File("d:/test.txt"))); System.out.println(s); JSONObject json = JSON.parseObject(s); System.out.println(json.getString("a")); System.out.println(json.getString("b")); System.out.println(json.getString("c")); } catch (Exception e) { e.printStackTrace(); } } }