一、前言
定义FileUtils文件工具类,实现根据指定文件名称读取内容为字符串(read)、指定文件名称和字符串内容进行写入(saveFile)操作,详情代码示例。
二、代码示例import java.io.BufferedReader;@b@import java.io.File;@b@import java.io.FileOutputStream;@b@import java.io.FileReader;@b@import java.io.IOException;@b@@b@public class FileUtils {@b@@b@private static String classPath = FileUtils.class.getResource("/")@b@.getPath();@b@@b@public static String read(String filename) throws IOException {@b@FileReader reader = new FileReader(classPath+filename);@b@BufferedReader in = null;@b@try {@b@in = new BufferedReader(reader);@b@StringBuilder sb = new StringBuilder();@b@String s=null;@b@while ((s = in.readLine()) != null) {@b@sb.append(new StringBuilder().append(s).append("\n").toString());@b@}@b@String str1 = sb.toString();@b@@b@return str1;@b@} finally {@b@if (in != null)@b@in.close();@b@}@b@}@b@@b@public static void saveFile(String fileName, String content)@b@throws Exception {@b@File file = new File(new StringBuilder().append(classPath)@b@.append(fileName).toString());@b@@b@if (file.exists()) {@b@file.delete();@b@saveFile(fileName, content);@b@} else {@b@String absolutepath = file.getAbsolutePath();@b@int lastIndex = absolutepath.lastIndexOf(File.separator);@b@@b@File dir = new File(absolutepath.substring(0, lastIndex));@b@if (!(dir.isDirectory()))@b@dir.mkdirs();@b@@b@file.createNewFile();@b@writFile(file, content);@b@}@b@}@b@@b@private static void writFile(File file, String content) throws Exception {@b@FileOutputStream fos = null;@b@try {@b@fos = new FileOutputStream(file);@b@byte[] buf = new byte[1024];@b@buf = content.getBytes();@b@fos.write(buf);@b@} finally {@b@if (fos != null)@b@fos.close();@b@}@b@}@b@@b@public static void main(String[] args) throws Exception{@b@saveFile("1.txt","写入测试数据");@b@@b@System.out.println(read("1.txt"));@b@}@b@@b@}
控制台打印结果写入测试数据@b@