一种常见的编程任务是,从一个文件读取内容,修改内容,再把内容写到另一个文件里。 Java 要实现读取、写入操作,需要创建多个类才能产生一个 Stream 进行操作。
下面是一个简单的工具类,封装对文件的读、写操作,提供简洁的接口。
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; public class TextFile { /** * * @param fileName The full path of the target file * @return */ public static String read(String fileName){ StringBuilder sb = new StringBuilder(); try { BufferedReader in = new BufferedReader(new FileReader(new File(fileName).getAbsoluteFile())); String s; try { while( (s = in.readLine()) != null ){ sb.append(s); sb.append("\n"); } }finally{ in.close(); } } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } /** * * @param fileName The full path of the target file * @param text The content which is written to the target file */ public static void write(String fileName, String text){ try { PrintWriter out = new PrintWriter(new File(fileName).getAbsoluteFile()); out.print(text); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
TextFile 工具类演示
public class TextFileDemo { public static void main(){ String fileName = "/tmp/dirTest/aaa.txt"; String content = TextFile.read(fileName); System.out.print(content); System.out.println("[ Read End ]"); String content2 = "aaaaaaaa"; TextFile.write(fileName, content2); } }
参考资料
Page 672, File reading & writing utilities, Thinking in Java 4th.
时间: 2024-10-23 04:21:59