首页 > 代码库 > 文件读写的工具类
文件读写的工具类
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 fileName16 */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 block23 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 args62 * @throws UnsupportedEncodingException 63 * @throws IOException64 */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 IOException76 */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 }
文件读写的工具类
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。