package text; import java.io.*; //文本文件操作类 public class file { private String fileName; public String getFileName() { return fileName; } //构造 private File file; public file(String fileName) { this.fileName = fileName; file = new File(fileName); } //创建文件 public void create() throws IOException { if(!file.exists())//如果文件不存在 { file.createNewFile(); System.out.println("文件创建成功!"); } else { System.out.println("文件已存在!"); } } //删除文件 public void delete() { File file = new File(fileName); if(file.exists())//如果文件存在 { file.delete(); System.out.println("删除成功!"); } else { System.out.println("文件不存在!"); } } //修改内容 public void edit(String strEdit) throws IOException//修改内容以参数形式传输进去 { if(file.exists()) { FileWriter fw = new FileWriter(file); BufferedWriter bfw = new BufferedWriter(fw); bfw.write(strEdit); bfw.close(); } else { System.out.println("文件不存在!"); } } //追加内容 public void addLine(String strLine) throws IOException//新加行,并传输内容 { if(file.exists()) { String str = readFile(); FileWriter fw = new FileWriter(file); BufferedWriter bfw = new BufferedWriter(fw); //bfw.newLine(); bfw.write(str+"\n"+strLine); bfw.close(); } else { System.out.println("文件不存在!"); } } public String readFile() throws IOException { String rtn = ""; if(file.exists()) { FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String s = ""; while((s = br.readLine()) != null) { rtn += s + "\n"; } br.close(); } else { System.out.println("文件不存在!"); } return rtn; } }
时间: 2024-12-19 00:03:11