文件读写的工具类
Posted 奔跑的大龙猫
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了文件读写的工具类相关的知识,希望对你有一定的参考价值。
1 package test; 2 3 import java.io.BufferedReader; 4 import java.io.File; 5 import java.io.FileOutputStream; 6 import java.io.FileReader; 7 import java.io.IOException; 8 import java.io.UnsupportedEncodingException; 9 import java.text.SimpleDateFormat; 10 import java.util.Date; 11 12 public class FileOperation { 13 /** 14 * 生成文件 15 * @param fileName 16 */ 17 public static boolean createFile(File fileName){ 18 if(!fileName.exists()){ 19 try { 20 fileName.createNewFile(); 21 } catch (Exception e) { 22 // TODO Auto-generated catch block 23 e.printStackTrace(); 24 } 25 } 26 return true; 27 } 28 29 /** 30 * @description 读文件 31 * @throws IOException 32 */ 33 public static String readTxtFile(File fileName) throws IOException{ 34 String result = null; 35 FileReader fileReader = null; 36 BufferedReader bufferedReader = null; 37 fileReader = new FileReader(fileName); 38 bufferedReader = new BufferedReader(fileReader); 39 40 String read = null; 41 int count = 0; 42 while((read = bufferedReader.readLine()) != null){ 43 result = result + count + read + "\r\n"; 44 count++; 45 } 46 47 if(bufferedReader != null){ 48 bufferedReader.close(); 49 } 50 51 if(fileReader != null){ 52 fileReader.close(); 53 } 54 55 System.out.println("¶ÁÈ¡ÎļþµÄÄÚÈÝÊÇ£º " + "\r\n" + result); 56 return result; 57 } 58 59 /** 60 * @description 写文件 61 * @param args 62 * @throws UnsupportedEncodingException 63 * @throws IOException 64 */ 65 public static boolean writeTxtFile(String content,File fileName) throws UnsupportedEncodingException, IOException{ 66 FileOutputStream o = null; 67 o = new FileOutputStream(fileName); 68 o.write(content.getBytes("UTF-8")); 69 o.close(); 70 return true; 71 } 72 73 /** 74 * @description 单元测试 75 * @throws IOException 76 */ 77 public static void main(String[] args) throws IOException { 78 File file = new File("d:/hello.txt"); 79 Date date = new Date(); 80 SimpleDateFormat day = new SimpleDateFormat("yyyyMMddHHmmss"); 81 String dateName = day.format(date); 82 File copyFile = new File("d:/" + dateName + ".txt"); 83 String content = readTxtFile(file); 84 createFile(copyFile); 85 writeTxtFile(content,copyFile); 86 } 87 }
以上是关于文件读写的工具类的主要内容,如果未能解决你的问题,请参考以下文章
solr分布式索引实战分片配置读取:工具类configUtil.java,读取配置代码片段,配置实例