1 package text; 2 3 import java.io.*; 4 5 //文本文件操作类 6 public class file { 7 8 private String fileName; 9 10 public String getFileName() 11 { 12 return fileName; 13 } 14 //构造 15 private File file; 16 17 public file(String fileName) 18 { 19 this.fileName = fileName; 20 21 file = new File(fileName); 22 } 23 24 //创建文件 25 public void create() throws IOException 26 { 27 28 29 if(!file.exists())//如果文件不存在 30 { 31 file.createNewFile(); 32 System.out.println("文件创建成功!"); 33 } 34 else 35 { 36 System.out.println("文件已存在!"); 37 } 38 } 39 //删除文件 40 public void delete() 41 { 42 File file = new File(fileName); 43 44 if(file.exists())//如果文件存在 45 { 46 file.delete(); 47 System.out.println("删除成功!"); 48 } 49 else 50 { 51 System.out.println("文件不存在!"); 52 } 53 } 54 //修改内容 55 public void edit(String strEdit) throws IOException//修改内容以参数形式传输进去 56 { 57 if(file.exists()) 58 { 59 FileWriter fw = new FileWriter(file); 60 61 BufferedWriter bfw = new BufferedWriter(fw); 62 63 bfw.write(strEdit); 64 65 bfw.close(); 66 } 67 else 68 { 69 System.out.println("文件不存在!"); 70 } 71 } 72 //追加内容 73 public void addLine(String strLine) throws IOException//新加行,并传输内容 74 { 75 if(file.exists()) 76 { 77 String str = readFile(); 78 79 FileWriter fw = new FileWriter(file); 80 81 BufferedWriter bfw = new BufferedWriter(fw); 82 83 //bfw.newLine(); 84 85 bfw.write(str+"\n"+strLine); 86 87 bfw.close(); 88 } 89 else 90 { 91 System.out.println("文件不存在!"); 92 } 93 } 94 public String readFile() throws IOException 95 { 96 String rtn = ""; 97 98 if(file.exists()) 99 { 100 FileReader fr = new FileReader(file); 101 102 BufferedReader br = new BufferedReader(fr); 103 104 String s = ""; 105 106 while((s = br.readLine()) != null) 107 { 108 rtn += s + "\n"; 109 } 110 br.close(); 111 } 112 else 113 { 114 System.out.println("文件不存在!"); 115 } 116 return rtn; 117 } 118 }
时间: 2024-10-08 20:04:41