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

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

【DataStructure】A useful util class for reading and writing files,布布扣,bubuko.com

时间: 2024-10-12 07:55:09

【DataStructure】A useful util class for reading and writing files的相关文章

【DataStructure】Description and usage of queue

[Description] A queue is a collection that implements the first-in-first-out protocal. This means that the only accessiable object in the collection in the first one that was inserted. The most common example of a queue is a waiting line. [Interface]

【DataStructure】One of queue usage: Simulation System

Statements: This blog was written by me, but most of content  is quoted from book[Data Structure with Java Hubbard] [Description] This simulationillustrates objectoriented programming(OOP). Java objects are instantiated to represent all the interacti

【DataStructure】Implemantation of Binary Tree

Statements: This blog was written by me, but most of content  is quoted from book[Data Structure with Java Hubbard] Here is a class for binary trees that directly implements the recursive definition. By extending the AbstractCollectionclass, it remai

【DataStructure】Another usage of List: Polynomial

Statements: This blog was written by me, but most of content  is quoted from book[Data Structure with Java Hubbard] [Description] Apolynomialis a mathematical function of the form: p(x) = a0xn+ a1xn–1+a2xn–2+ ???+an–1x + an The greatest exponent, 

【DataStructure】 Classical Question: Josephus Cycle

[Description] This problem is based upon a report by the historian Joseph ben Matthias (Josephus) on the outcome of a suicide pact that he had made between himself and 40 soldiers as they were besieged by superior Roman forces in 67 A.D. Josephus pro

【DataStructure】 Five methods to init the List in java

Do you know how to init list in other way except for new object? The following will give you serveral tips. If having other great idea, you are welcome to share. [java] view plaincopy import java.util.ArrayList; import java.util.Arrays; import java.u

【DataStructure】Charming usage of Set in the java

In an attempt to remove duplicate elements from list, I go to the lengths to take advantage of  methods in the java api. After investiagting the document of java api, the result is so satisfying that I speak hightly of wisdom of developer of java lan

【DataStructure】Descriptioin and usage of List

Statements: This blog was written by me, but most of content  is quoted from book[Data Structure with Java Hubbard] [Description] Alistis a collection of elements that are accessible sequentially: the first element, followed by the second element, fo

【DataStructure】The description of generic collections

In this blog, generic collections will be talked about  in details.  In the past bacause of shortage of generic argument,  less importance has been attached to the this module. Just now after reading the chapter about this knowledge, I gradually real