现在的位置: 首页 > 综合 > 正文

【DataStructure】A useful util class for reading and writing files

2017年11月01日 ⁄ 综合 ⁄ 共 7974字 ⁄ 字号 评论关闭

Faced with the upcoming exam, Some useful methods referred to file operation drew tremenous attention. Now I make a summary to reading file.

[java] view
plain
copy

  1. import java.io.BufferedReader;  
  2. import java.io.BufferedWriter;  
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileNotFoundException;  
  6. import java.io.FileOutputStream;  
  7. import java.io.IOException;  
  8. import java.io.InputStreamReader;  
  9. import java.io.OutputStreamWriter;  
  10. import java.util.ArrayList;  
  11. import java.util.HashMap;  
  12. import java.util.List;  
  13. import java.util.Map;  
  14.   
  15. public class FileUtil  
  16. {  
  17.   
  18.     public static final String SEP = ":";  
  19.   
  20.     public static final String ENCODING = "UTF-8";  
  21.   
  22.     /** 
  23.      * Read the content from file, the format of content is like "Key:Value" 
  24.      * TODO 
  25.      *  
  26.      * @time Jul 17, 2014 11:21:50 AM 
  27.      * @param filePath 
  28.      * @return 
  29.      * @throws Exception 
  30.      * @return Map<String,String> 
  31.      */  
  32.     public static Map<String, String> readFileToMap(String filePath)  
  33.             throws Exception  
  34.     {  
  35.         System.out.println("读文件[" + filePath + "]开始...");  
  36.   
  37.         Map<String, String> contents = new HashMap<String, String>();  
  38.   
  39.         File file = new File(filePath);  
  40.         BufferedReader reader = null;  
  41.   
  42.         try  
  43.         {  
  44.             reader = new BufferedReader(new InputStreamReader(  
  45.                     new FileInputStream(file), ENCODING));  
  46.             String info = null;  
  47.   
  48.             while ((info = reader.readLine()) != null)  
  49.             {  
  50.                 contents.put(info.split(SEP)[0], info.split(SEP)[1]);  
  51.             }  
  52.         }  
  53.         catch (FileNotFoundException e)  
  54.         {  
  55.             System.out.println("文件[" + filePath + "]未找到.");  
  56.             throw e;  
  57.         }  
  58.         catch (IOException e)  
  59.         {  
  60.             System.out.println("文件IO操作出错, 异常信息: " + e.getMessage());  
  61.             throw e;  
  62.         }  
  63.         catch (Exception e)  
  64.         {  
  65.             System.out.println("读文件出错, 异常信息: " + e.getMessage());  
  66.             throw e;  
  67.         }  
  68.         finally  
  69.         {  
  70.             if (reader != null)  
  71.             {  
  72.                 try  
  73.                 {  
  74.                     reader.close();  
  75.                 }  
  76.                 catch (IOException e)  
  77.                 {  
  78.                     System.out.println("关闭IO流出错, 异常信息: " + e.getMessage());  
  79.                     throw e;  
  80.                 }  
  81.             }  
  82.         }  
  83.   
  84.         System.out.println("读文件[" + filePath + "]结束.");  
  85.   
  86.         return contents;  
  87.     }  
  88.   
  89.     /** 
  90.      * Read the content from file, every line will be an element of list. 
  91.      *  
  92.      * @time Jul 17, 2014 11:39:07 AM 
  93.      * @param fileName 
  94.      * @return 
  95.      * @return List<String> 
  96.      */  
  97.     public static List<String> readFileToList(String fileName) throws Exception  
  98.     {  
  99.         List<String> infos = new ArrayList<String>();  
  100.   
  101.         BufferedReader reader = null;  
  102.   
  103.         try  
  104.         {  
  105.             reader = new BufferedReader(new InputStreamReader(  
  106.                     new FileInputStream(new File(fileName)), "utf-8"));  
  107.             String info = null;  
  108.             while ((info = reader.readLine()) != null)  
  109.             {  
  110.                 infos.add(info);  
  111.             }  
  112.         }  
  113.         catch (FileNotFoundException e)  
  114.         {  
  115.             System.out.println("文件[" + fileName + "]未找到.");  
  116.             throw e;  
  117.         }  
  118.         catch (IOException e)  
  119.         {  
  120.             System.out.println("文件IO操作出错, 异常信息: " + e.getMessage());  
  121.             throw e;  
  122.         }  
  123.         finally  
  124.         {  
  125.             try  
  126.             {  
  127.                 if (reader != null)  
  128.                 {  
  129.                     reader.close();  
  130.                 }  
  131.             }  
  132.             catch (IOException e)  
  133.             {  
  134.                 e.printStackTrace();  
  135.             }  
  136.         }  
  137.   
  138.         return infos;  
  139.     }  
  140.   
  141.     /** 
  142.      * Read all the content from filePath at a time. 
  143.      *  
  144.      * @time Jul 17, 2014 11:45:55 AM 
  145.      * @param filePathOrFileName 
  146.      * @return 
  147.      * @return String 
  148.      */  
  149.     public static String readFileToString(String filePath) throws Exception  
  150.     {  
  151.         InputStreamReader isReder = null;  
  152.         BufferedReader br = null;  
  153.         StringBuffer sb = new StringBuffer();  
  154.         try  
  155.         {  
  156.             File f = new File(filePath);  
  157.             if (f.isFile() && f.exists())  
  158.             {  
  159.                 isReder = new InputStreamReader(new FileInputStream(f), "UTF-8");  
  160.                 br = new BufferedReader(isReder);  
  161.                 String line;  
  162.                 while ((line = br.readLine()) != null)  
  163.                 {  
  164.                     sb.append(line).append("\r\n");  
  165.                 }  
  166.             }  
  167.         }  
  168.         catch (Exception e)  
  169.         {  
  170.             System.out.println("exception when reading the file" + filePath);  
  171.             throw e;  
  172.         }  
  173.         finally  
  174.         {  
  175.             if (isReder != null)  
  176.             {  
  177.                 try  
  178.                 {  
  179.                     isReder.close();  
  180.                 }  
  181.                 catch (IOException e)  
  182.                 {  
  183.                     e.getMessage();  
  184.                 }  
  185.             }  
  186.             if (br != null)  
  187.             {  
  188.                 try  
  189.                 {  
  190.                     br.close();  
  191.                 }  
  192.                 catch (IOException e)  
  193.                 {  
  194.                     e.getMessage();  
  195.                 }  
  196.             }  
  197.         }  
  198.         return sb.toString();  
  199.     }  
  200.   
  201.     /** 
  202.      * Write result to the fileName 
  203.      *  
  204.      * @time Jul 17, 2014 4:57:57 PM 
  205.      * @param result 
  206.      * @param fileName 
  207.      * @return void 
  208.      */  
  209.     public static void writeFile(String result, String fileName)  
  210.     {  
  211.         File f = new File(fileName);  
  212.         OutputStreamWriter osw = null;  
  213.         BufferedWriter bw = null;  
  214.         try  
  215.         {  
  216.             if (!f.exists())  
  217.             {  
  218.                 f.createNewFile();  
  219.             }  
  220.             osw = new OutputStreamWriter(new FileOutputStream(f), "UTF-8"); //"gbk"  
  221.               
  222.             bw = new BufferedWriter(osw);  
  223.             bw.write(result);  
  224.         }  
  225.         catch (IOException e)  
  226.         {  
  227.             System.out.println("IOException when writing result, "  
  228.                     + e.getMessage());  
  229.         }  
  230.         catch (Exception e)  
  231.         {  
  232.             System.out.println("Exception when writing result, "  
  233.                     + e.getMessage());  
  234.         }  
  235.         finally  
  236.         {  
  237.             if (bw != null)  
  238.             {  
  239.                 try  
  240.                 {  
  241.                     bw.close();  
  242.                 }  
  243.                 catch (IOException e)  
  244.                 {  
  245.                     System.out.println("IOException when closing FileWriter, "  
  246.                             + e.getMessage());  
  247.                 }  
  248.             }  
  249.               
  250.             if (osw != null)  
  251.             {  
  252.                 try  
  253.                 {  
  254.                     osw.close();  
  255.                 }  
  256.                 catch (IOException e)  
  257.                 {  
  258.                     System.out.println("IOException when closing bufferwriter, "  
  259.                             + e.getMessage());  
  260.                 }  
  261.             }  
  262.         }  
  263.     }  
  264.   
  265.     public static void main(String[] args) throws Exception  
  266.     {  
  267.         Map<String, String> testMap = FileUtil.readFileToMap("input.txt");  
  268.         System.out.println("---------------------");  
  269.         for (Map.Entry<String, String> entry : testMap.entrySet())  
  270.         {  
  271.             System.out.println(entry.getKey() + ":" + entry.getValue());  
  272.         }  
  273.   
  274.         System.out.println("---------------------");  
  275.   
  276.         List<String> testList = FileUtil.readFileToList("input.txt");  
  277.   
  278.         for (String str : testList)  
  279.         {  
  280.             System.out.println(str);  
  281.         }  
  282.         System.out.println("---------------------");  
  283.         String test = FileUtil.readFileToString("input.txt");  
  284.         FileUtil.writeFile(test, "output.txt");  
  285.     }  
  286. }  

抱歉!评论已关闭.