├── .gitignore ├── README.md ├── Web-Security-Monitored.iml ├── config.properties ├── lib ├── commons-logging-1.1.1.jar ├── httpclient-4.5.1.jar └── httpcore-4.4.4.jar ├── out ├── artifacts │ └── Web_Security_Monitored_jar │ │ └── Web-Security-Monitored.jar └── production │ └── Web-Security-Monitored │ ├── META-INF │ └── MANIFEST.MF │ └── com │ └── superl │ ├── ChuanglanSMS.class │ ├── Main.class │ ├── MyService.class │ └── ReadWriteFile.class └── src ├── META-INF └── MANIFEST.MF └── com └── superl ├── ChuanglanSMS.java ├── Main.java ├── MyService.java └── ReadWriteFile.java /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .DS_Store 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Web-Security-Monitored 跨平台服务器文件安全监控工具 ## 使用说明: 软件需要安装java运行环境。并设置java的相关环境变量。安装JAVA和设置环境变量的方法请搜索百度。 检测环境是否成功: java -version ## 运行方法: 命令行下输入:java -jar Web-Security-Monitored.jar 运行完毕后,即可开始监控。 ## 使用效果: * Last login: Tue Apr 11 20:01:05 on ttys000 * superldeMacBook-Pro:~ superl$ cd /Users/superl/tools/原创源码/Web\ Security\ Monitored * superldeMacBook-Pro:Web Security Monitored superl$ java -jar Web-Security-Monitored.jar * start MyWatcherService ... * 文件:/Users/superl/Desktop/test.php被新建,时间:2017-04-11 20:03:01 * {"success": true, "id":"17041120030239600"} * 短信发送成功,内容为:文件:/Users/superl/Desktop/test.php被新建,时间:2017-04-11 20:03:01 ## 配置文件说明: 软件运行之前,需要根据自己的需求,修改配置config.properties。 ### 例子: * monitored_path=/Users/superl/Desktop 要监控的路径 * check_prefix=true 是否只监控指定后缀的文件 * file_prefix=php 要监控的文件后缀,如php * monitored_directory=false 是否监控目录的操作,默认不监控 * monitored_move_delete=false 是否监控文件的移动和删除操作,默认不监控 * ruledout_dir=/Users/superl/Desktop/test,/Users/superl/Desktop/java,/Users/superl/Desktop/notorm 不监控的路径白名单 * mobile=181xxxxxxxx 短信通知的手机号码 * username=xxxxxx 短信平台的账号 * password=xxxxxx 短信平台的密码 ### 友情提示 ruledout_dir表示不监控的路径白名单。请填写绝对路径。 如果是windows系统,请填写格式如:d:/wwwroot/www/upload 如果有多个目录不需要监控,请用英文逗号【,】隔开。 ## 使用步骤: 1. 先配置好配置文件; 2. 把Web-Security-Monitored.jar和config.properties复制到d:/safetools 3. 打开命令提示符,使用cd命令切换到d:/safetools。(命令:cd d:/safetools) 4. 输入java -jar Web-Security-Monitored.jar 命令即可。 -------------------------------------------------------------------------------- /Web-Security-Monitored.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /config.properties: -------------------------------------------------------------------------------- 1 | monitored_path=/Users/superl/Desktop 2 | check_prefix=true 3 | file_prefix=php 4 | monitored_directory=false 5 | monitored_move_delete=false 6 | ruledout_dir=/Users/superl/Desktop/cpts,/Users/superl/Desktop/test,/Users/superl/Desktop/测试 7 | mobile=181xxxxxxxx 8 | username=xxxxxxxx 9 | password=xxxxxxxx -------------------------------------------------------------------------------- /lib/commons-logging-1.1.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/super-l/Web-Security-Monitored/cf828a74f5a71c55dcdca26f877acc5f0f6f9aed/lib/commons-logging-1.1.1.jar -------------------------------------------------------------------------------- /lib/httpclient-4.5.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/super-l/Web-Security-Monitored/cf828a74f5a71c55dcdca26f877acc5f0f6f9aed/lib/httpclient-4.5.1.jar -------------------------------------------------------------------------------- /lib/httpcore-4.4.4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/super-l/Web-Security-Monitored/cf828a74f5a71c55dcdca26f877acc5f0f6f9aed/lib/httpcore-4.4.4.jar -------------------------------------------------------------------------------- /out/artifacts/Web_Security_Monitored_jar/Web-Security-Monitored.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/super-l/Web-Security-Monitored/cf828a74f5a71c55dcdca26f877acc5f0f6f9aed/out/artifacts/Web_Security_Monitored_jar/Web-Security-Monitored.jar -------------------------------------------------------------------------------- /out/production/Web-Security-Monitored/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Main-Class: com.superl.Main 3 | 4 | -------------------------------------------------------------------------------- /out/production/Web-Security-Monitored/com/superl/ChuanglanSMS.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/super-l/Web-Security-Monitored/cf828a74f5a71c55dcdca26f877acc5f0f6f9aed/out/production/Web-Security-Monitored/com/superl/ChuanglanSMS.class -------------------------------------------------------------------------------- /out/production/Web-Security-Monitored/com/superl/Main.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/super-l/Web-Security-Monitored/cf828a74f5a71c55dcdca26f877acc5f0f6f9aed/out/production/Web-Security-Monitored/com/superl/Main.class -------------------------------------------------------------------------------- /out/production/Web-Security-Monitored/com/superl/MyService.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/super-l/Web-Security-Monitored/cf828a74f5a71c55dcdca26f877acc5f0f6f9aed/out/production/Web-Security-Monitored/com/superl/MyService.class -------------------------------------------------------------------------------- /out/production/Web-Security-Monitored/com/superl/ReadWriteFile.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/super-l/Web-Security-Monitored/cf828a74f5a71c55dcdca26f877acc5f0f6f9aed/out/production/Web-Security-Monitored/com/superl/ReadWriteFile.class -------------------------------------------------------------------------------- /src/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Main-Class: com.superl.Main 3 | 4 | -------------------------------------------------------------------------------- /src/com/superl/ChuanglanSMS.java: -------------------------------------------------------------------------------- 1 | package com.superl; 2 | 3 | 4 | /** 5 | * @Package com.superl 6 | * @Description 创蓝短信接口 7 | * @Author superl www.superl.org 8 | * @Date 2017/4/11 下午5:59 9 | * @Version V1.0 10 | */ 11 | 12 | import org.apache.http.client.ClientProtocolException; 13 | import org.apache.http.client.methods.CloseableHttpResponse; 14 | import org.apache.http.client.methods.HttpGet; 15 | import org.apache.http.impl.client.CloseableHttpClient; 16 | import org.apache.http.impl.client.HttpClients; 17 | 18 | import java.io.IOException; 19 | import java.io.UnsupportedEncodingException; 20 | import java.net.URLEncoder; 21 | 22 | public class ChuanglanSMS { 23 | private CloseableHttpClient client; 24 | private String account; 25 | private String password; 26 | private static final String SEND_URL="http://222.73.117.138:7891/mt"; 27 | private static final String QUERY_URL="http://222.73.117.138:7891/bi"; 28 | private static final String INTERNATIONAL_URL="http://222.73.117.140:8044/mt"; 29 | 30 | public ChuanglanSMS(String account,String password){ 31 | this.account = account; 32 | this.password = password; 33 | client = HttpClients.createDefault(); 34 | //System.out.println(account); 35 | } 36 | 37 | public CloseableHttpResponse sendMessage(String phone, String content) { 38 | String encodedContent = null; 39 | try { 40 | encodedContent = URLEncoder.encode(content, "utf-8"); 41 | } catch (UnsupportedEncodingException e) { 42 | e.printStackTrace(); 43 | return null; 44 | } 45 | StringBuffer strBuf = new StringBuffer(SEND_URL); 46 | strBuf.append("?un=").append(account); 47 | strBuf.append("&pw=").append(password); 48 | strBuf.append("&da=").append(phone); 49 | strBuf.append("&sm=").append(encodedContent); 50 | strBuf.append("&dc=15&rd=1&rf=2&tf=3"); 51 | HttpGet get = new HttpGet( strBuf.toString() ); 52 | 53 | try { 54 | return client.execute(get); 55 | } catch (ClientProtocolException e) { 56 | e.printStackTrace(); 57 | } catch (IOException e) { 58 | e.printStackTrace(); 59 | } 60 | return null; 61 | } 62 | 63 | public CloseableHttpResponse queryBalance() { 64 | StringBuffer strBuf = new StringBuffer(QUERY_URL); 65 | strBuf.append("?un=").append(account); 66 | strBuf.append("&pw=").append(password); 67 | strBuf.append("&rf=2"); 68 | HttpGet get = new HttpGet( strBuf.toString() ); 69 | 70 | try { 71 | return client.execute(get); 72 | } catch (ClientProtocolException e) { 73 | e.printStackTrace(); 74 | } catch (IOException e) { 75 | e.printStackTrace(); 76 | } 77 | return null; 78 | } 79 | 80 | public CloseableHttpResponse sendInternationalMessage(String phone, String content) { 81 | String encodedContent = null; 82 | try { 83 | encodedContent = URLEncoder.encode(content, "utf-8"); 84 | } catch (UnsupportedEncodingException e) { 85 | e.printStackTrace(); 86 | return null; 87 | } 88 | StringBuffer strBuf = new StringBuffer(INTERNATIONAL_URL); 89 | strBuf.append("?un=").append(account); 90 | strBuf.append("&pw=").append(password); 91 | strBuf.append("&da=").append(phone); 92 | strBuf.append("&sm=").append(encodedContent); 93 | strBuf.append("&dc=15&rd=1&rf=2&tf=3"); 94 | HttpGet get = new HttpGet( strBuf.toString() ); 95 | 96 | try { 97 | return client.execute(get); 98 | } catch (ClientProtocolException e) { 99 | e.printStackTrace(); 100 | } catch (IOException e) { 101 | e.printStackTrace(); 102 | } 103 | return null; 104 | } 105 | 106 | public void close() { 107 | if(client != null){ 108 | try { 109 | client.close(); 110 | } catch (IOException e) { 111 | e.printStackTrace(); 112 | } 113 | } 114 | } 115 | 116 | public String getAccount() { 117 | return account; 118 | } 119 | 120 | public void setAccount(String account) { 121 | this.account = account; 122 | } 123 | 124 | public String getPassword() { 125 | return password; 126 | } 127 | 128 | public void setPassword(String password) { 129 | this.password = password; 130 | } 131 | 132 | } 133 | -------------------------------------------------------------------------------- /src/com/superl/Main.java: -------------------------------------------------------------------------------- 1 | package com.superl; 2 | import java.io.IOException; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args) throws IOException, InterruptedException{ 7 | System.err.println("start MyWatcherService ..."); 8 | 9 | /* 10 | ChuanglanSMS client = new ChuanglanSMS("xxxxx","xxxxx"); 11 | CloseableHttpResponse response = null; 12 | try { 13 | //发送短信 14 | response = client.sendMessage("181xxxxxxxx","验证码为xxxxxxxx"); 15 | if(response != null && response.getStatusLine().getStatusCode()==200){ 16 | System.out.println(EntityUtils.toString(response.getEntity())); 17 | } 18 | } catch (ParseException e) { 19 | e.printStackTrace(); 20 | } catch (IOException e) { 21 | e.printStackTrace(); 22 | } 23 | client.close(); 24 | */ 25 | 26 | MyService myWatcherService = new MyService(); 27 | myWatcherService.initialize(); 28 | myWatcherService.doMonitor(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/com/superl/MyService.java: -------------------------------------------------------------------------------- 1 | package com.superl; 2 | 3 | /** 4 | * @author superl www.superl.org 5 | * @version V1.0 6 | * @Package com.superl 7 | * @Description 监控功能 8 | * @date 2017/4/11 下午6:07 9 | */ 10 | 11 | import org.apache.http.client.methods.CloseableHttpResponse; 12 | import org.apache.http.util.EntityUtils; 13 | import org.apache.http.ParseException; 14 | import java.io.*; 15 | import java.nio.file.*; 16 | import java.text.SimpleDateFormat; 17 | import java.util.Arrays; 18 | import java.util.Date; 19 | import java.util.LinkedList; 20 | import java.util.Properties; 21 | 22 | import static java.nio.file.StandardWatchEventKinds.*; 23 | 24 | public class MyService { 25 | 26 | private WatchService watchService = null; 27 | 28 | private String filePrefix; 29 | private String monitoredPath; 30 | private Boolean checkPrefix; 31 | private Boolean monitoredDir; 32 | private Boolean monitoredMD; 33 | private String ruledoutDir; 34 | private String mobileNum; 35 | private String userName; 36 | private String passWord; 37 | 38 | private String smsContent; 39 | private String eventMethod; 40 | 41 | public void initialize() throws IOException{ 42 | 43 | Properties prop = new Properties(); 44 | InputStream inputStream = new FileInputStream("config.properties"); 45 | BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream, "utf-8")); 46 | prop.load(bf); 47 | inputStream.close(); // 关闭流 48 | 49 | /* 50 | InputStream in = new BufferedInputStream(new FileInputStream("config.properties")); 51 | Properties prop = new Properties(); 52 | prop.load(in); 53 | */ 54 | 55 | filePrefix = prop.getProperty("file_prefix"); 56 | monitoredPath = prop.getProperty("monitored_path"); 57 | checkPrefix = new Boolean(prop.getProperty("check_prefix")); 58 | monitoredDir = new Boolean(prop.getProperty("monitored_directory")); 59 | monitoredMD = new Boolean(prop.getProperty("monitored_move_delete")); 60 | ruledoutDir = prop.getProperty("ruledout_dir"); 61 | mobileNum = prop.getProperty("mobile"); 62 | userName = prop.getProperty("username"); 63 | passWord = prop.getProperty("password"); 64 | //System.out.println(ruledoutDir); 测试是否中文乱码 65 | 66 | watchService = FileSystems.getDefault().newWatchService(); 67 | Paths.get(monitoredPath).register(watchService, ENTRY_CREATE,ENTRY_DELETE,ENTRY_MODIFY); 68 | 69 | File file = new File(monitoredPath); 70 | LinkedList fList = new LinkedList(); 71 | fList.addLast(file); 72 | while (fList.size() > 0 ) { 73 | File f = fList.removeFirst(); 74 | if(f.listFiles() == null) 75 | continue; 76 | for(File file2 : f.listFiles()){ 77 | if (file2.isDirectory()){//下一级目录 78 | fList.addLast(file2); 79 | //依次注册子目录 80 | Paths.get(file2.getAbsolutePath()).register(watchService 81 | , StandardWatchEventKinds.ENTRY_CREATE 82 | , StandardWatchEventKinds.ENTRY_MODIFY 83 | , StandardWatchEventKinds.ENTRY_DELETE); 84 | } 85 | } 86 | } 87 | } 88 | 89 | public void doMonitor() throws InterruptedException,IOException{ 90 | final Properties PROPERTIES = new Properties(System.getProperties()); 91 | String separator = PROPERTIES.getProperty("file.separator"); 92 | 93 | while(true){ 94 | try { 95 | WatchKey key = watchService.take(); 96 | for(WatchEvent event : key.pollEvents()){ 97 | WatchEvent.Kind kind = event.kind(); 98 | 99 | if(kind == OVERFLOW){ 100 | //事件可能lost or discarded 101 | continue; 102 | } 103 | 104 | WatchEvent e = (WatchEvent)event; 105 | //获取路径 106 | Path path = (Path) key.watchable(); 107 | //获取分隔符号 108 | String fullpath = path.toString()+separator; 109 | //获取文件名 110 | Path fileName = e.context(); 111 | //拼接文件名称和路径 112 | String filepath = fullpath+fileName; 113 | //获取文件后缀 114 | String prefix = fileName.toString().substring(fileName.toString().lastIndexOf(".")+1); 115 | 116 | File theFile = new File(filepath); 117 | 118 | 119 | 120 | //判断是文件还是目录 121 | if(theFile.isFile()){ 122 | //判断是否是白名单目录 123 | String[] ruledoutDirArray = ruledoutDir.split(","); 124 | Boolean haveStr = false; 125 | if(ruledoutDirArray!=null||ruledoutDirArray.length!=0){ 126 | haveStr = Arrays.asList(ruledoutDirArray).contains(path.toString()); 127 | }else{ 128 | haveStr = false; 129 | } 130 | if(!haveStr){ 131 | if(checkPrefix){ 132 | if(prefix.equals(filePrefix)){ 133 | if(kind.toString().equals("ENTRY_CREATE")){ 134 | eventMethod = "被新建"; 135 | }else if (kind.toString().equals("ENTRY_MODIFY")){ 136 | eventMethod = "被修改"; 137 | }else{ 138 | eventMethod = "被操作"; 139 | } 140 | SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 141 | smsContent = "文件:"+filepath+eventMethod+",时间:"+df.format(new Date()); 142 | 143 | //输出提示信息 144 | System.out.println(smsContent); 145 | 146 | //发送提示信息到手机短信 147 | ChuanglanSMS client = new ChuanglanSMS(userName,passWord); 148 | CloseableHttpResponse response = null; 149 | try { 150 | response = client.sendMessage(mobileNum,smsContent); 151 | if(response != null && response.getStatusLine().getStatusCode()==200){ 152 | System.out.println(EntityUtils.toString(response.getEntity())); 153 | System.out.println("短信发送成功,内容为:"+smsContent); 154 | } 155 | }catch (ParseException p1) { 156 | System.out.println("短信发送成失败"); 157 | p1.printStackTrace(); 158 | }catch (IOException i1) { 159 | System.out.println("短信发送成失败"); 160 | i1.printStackTrace(); 161 | } 162 | client.close(); 163 | 164 | } 165 | }else{ 166 | if(kind.toString().equals("ENTRY_CREATE")){ 167 | eventMethod = "被新建"; 168 | }else if (kind.toString().equals("ENTRY_MODIFY")){ 169 | eventMethod = "被修改"; 170 | }else{ 171 | eventMethod = "被操作"; 172 | } 173 | SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 174 | smsContent = "文件:"+filepath+eventMethod+",时间:"+df.format(new Date()); 175 | 176 | //输出提示信息 177 | System.out.println(smsContent); 178 | 179 | //发送提示信息到手机短信 180 | ChuanglanSMS client = new ChuanglanSMS(userName,passWord); 181 | CloseableHttpResponse response = null; 182 | try { 183 | response = client.sendMessage(mobileNum,smsContent); 184 | if(response != null && response.getStatusLine().getStatusCode()==200){ 185 | System.out.println(EntityUtils.toString(response.getEntity())); 186 | System.out.println("短信发送成功,内容为:"+smsContent); 187 | } 188 | }catch (ParseException p1) { 189 | System.out.println("短信发送成失败"); 190 | p1.printStackTrace(); 191 | }catch (IOException i1) { 192 | System.out.println("短信发送成失败"); 193 | i1.printStackTrace(); 194 | } 195 | client.close(); 196 | 197 | } 198 | }else{ 199 | //不监控白名单目录 200 | } 201 | }else if(theFile.isDirectory()){ 202 | //System.out.println("这是目录类型"); 203 | 204 | //判断是否是白名单目录 205 | String[] ruledoutDirArray = ruledoutDir.split("||"); 206 | Boolean haveStr; 207 | if(ruledoutDirArray!=null||ruledoutDirArray.length!=0){ 208 | haveStr = Arrays.asList(ruledoutDirArray).contains(fullpath); 209 | }else{ 210 | haveStr = false; 211 | } 212 | if(!haveStr){ 213 | if(monitoredDir){ 214 | if(kind.toString().equals("ENTRY_CREATE")){ 215 | eventMethod = "被新建"; 216 | }else if (kind.toString().equals("ENTRY_MODIFY")){ 217 | eventMethod = "被修改"; 218 | }else{ 219 | eventMethod = "被操作"; 220 | } 221 | SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 222 | smsContent = "文件:"+filepath+eventMethod+",时间:"+df.format(new Date()); 223 | 224 | //输出提示信息 225 | System.out.println(smsContent); 226 | 227 | //发送提示信息到手机短信 228 | ChuanglanSMS client = new ChuanglanSMS(userName,passWord); 229 | CloseableHttpResponse response = null; 230 | try { 231 | response = client.sendMessage(mobileNum,smsContent); 232 | if(response != null && response.getStatusLine().getStatusCode()==200){ 233 | System.out.println(EntityUtils.toString(response.getEntity())); 234 | System.out.println("短信发送成功,内容为:"+smsContent); 235 | } 236 | }catch (ParseException p1) { 237 | System.out.println("短信发送成失败"); 238 | p1.printStackTrace(); 239 | }catch (IOException i1) { 240 | System.out.println("短信发送成失败"); 241 | i1.printStackTrace(); 242 | } 243 | client.close(); 244 | }else{ 245 | //不监控目录类型 246 | } 247 | } 248 | }else{ 249 | //文件被删除,被移动 250 | 251 | //判断是否是白名单目录 252 | String[] ruledoutDirArray = ruledoutDir.split("||"); 253 | Boolean haveStr; 254 | if(ruledoutDirArray!=null||ruledoutDirArray.length!=0){ 255 | haveStr = Arrays.asList(ruledoutDirArray).contains(fullpath); 256 | }else{ 257 | haveStr = false; 258 | } 259 | 260 | if(!haveStr){ 261 | if(monitoredMD){ 262 | if(checkPrefix){ 263 | if(prefix.equals(filePrefix)){ 264 | if(kind.toString().equals("ENTRY_CREATE")){ 265 | eventMethod = "新建操作"; 266 | }else if (kind.toString().equals("ENTRY_MODIFY")){ 267 | eventMethod = "修改操作"; 268 | }else{ 269 | eventMethod = "其他操作"; 270 | } 271 | SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 272 | smsContent = "文件:"+filepath+" 发生了"+eventMethod+" 操作时间:"+df.format(new Date()); 273 | 274 | System.out.println(smsContent); 275 | 276 | ReadWriteFile myfile = new ReadWriteFile(); 277 | myfile.creatTxtFile(); 278 | myfile.writeTxtFile(smsContent); 279 | } 280 | }else{ 281 | //System.out.printf("Event %s has happened,which fileName is %s%n",kind,filepath); 282 | if(kind.toString().equals("ENTRY_CREATE")){ 283 | eventMethod = "新建操作"; 284 | }else if (kind.toString().equals("ENTRY_MODIFY")){ 285 | eventMethod = "修改操作"; 286 | }else{ 287 | eventMethod = "其他操作"; 288 | } 289 | SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 290 | smsContent = "文件:"+filepath+" 发生了"+eventMethod+" 操作时间:"+df.format(new Date()); 291 | 292 | System.out.println(smsContent); 293 | 294 | ReadWriteFile myfile = new ReadWriteFile(); 295 | myfile.creatTxtFile(); 296 | myfile.writeTxtFile(smsContent); 297 | } 298 | }else{ 299 | //配置文件设置了不监控文件被删除和移动操作 300 | } 301 | } 302 | } 303 | } 304 | if(!key.reset()){ 305 | break; 306 | } 307 | } catch (InterruptedException e) { 308 | System.out.println("InterruptedException: " + e.getMessage()); 309 | } 310 | } 311 | } 312 | } 313 | -------------------------------------------------------------------------------- /src/com/superl/ReadWriteFile.java: -------------------------------------------------------------------------------- 1 | package com.superl; 2 | 3 | /** 4 | * @author superl www.superl.org 5 | * @version V1.0 6 | * @Package com.superl 7 | * @Description 读写文件操作类 8 | * @date 2017/4/11 下午6:09 9 | */ 10 | 11 | import java.io.*; 12 | 13 | public class ReadWriteFile { 14 | 15 | public static BufferedReader bufread; 16 | //指定文件路径和名称 17 | private static String path = "log.txt"; 18 | private static File filename = new File(path); 19 | private static String readStr =""; 20 | 21 | 22 | /** 23 | * 创建文本文件. 24 | * @throws IOException 25 | * 26 | */ 27 | public static void creatTxtFile() throws IOException{ 28 | if (!filename.exists()) { 29 | filename.createNewFile(); 30 | //System.err.println(filename + "已创建!"); 31 | } 32 | } 33 | 34 | /** 35 | * 读取文本文件. 36 | * 37 | */ 38 | public static String readTxtFile(){ 39 | String read; 40 | FileReader fileread; 41 | try { 42 | fileread = new FileReader(filename); 43 | bufread = new BufferedReader(fileread); 44 | try { 45 | while ((read = bufread.readLine()) != null) { 46 | readStr = readStr + read+ "\r\n"; 47 | } 48 | } catch (IOException e) { 49 | // TODO Auto-generated catch block 50 | e.printStackTrace(); 51 | } 52 | } catch (FileNotFoundException e) { 53 | // TODO Auto-generated catch block 54 | e.printStackTrace(); 55 | } 56 | 57 | //System.out.println("文件内容是:"+ "\r\n" + readStr); 58 | return readStr; 59 | } 60 | 61 | /** 62 | * 写文件 63 | */ 64 | public static void writeTxtFile(String newStr) throws IOException{ 65 | //先读取原有文件内容,然后进行写入操作 66 | String filein = newStr + "\r\n" + readStr + "\r\n"; 67 | RandomAccessFile mm = null; 68 | try { 69 | mm = new RandomAccessFile(filename, "rw"); 70 | mm.writeBytes(filein); 71 | } catch (IOException e1) { 72 | // TODO 自动生成 catch 块 73 | e1.printStackTrace(); 74 | } finally { 75 | if (mm != null) { 76 | try { 77 | mm.close(); 78 | } catch (IOException e2) { 79 | // TODO 自动生成 catch 块 80 | e2.printStackTrace(); 81 | } 82 | } 83 | } 84 | } 85 | 86 | /** 87 | * 将文件中指定内容的第一行替换为其它内容. 88 | * 89 | * @param oldStr 查找内容 90 | * @param replaceStr 替换内容 91 | */ 92 | public static void replaceTxtByStr(String oldStr,String replaceStr) { 93 | String temp = ""; 94 | try { 95 | File file = new File(path); 96 | FileInputStream fis = new FileInputStream(file); 97 | InputStreamReader isr = new InputStreamReader(fis); 98 | BufferedReader br = new BufferedReader(isr); 99 | StringBuffer buf = new StringBuffer(); 100 | 101 | // 保存该行前面的内容 102 | for (int j = 1; (temp = br.readLine()) != null 103 | && !temp.equals(oldStr); j++) { 104 | buf = buf.append(temp); 105 | buf = buf.append(System.getProperty("line.separator")); 106 | } 107 | 108 | // 将内容插入 109 | buf = buf.append(replaceStr); 110 | 111 | // 保存该行后面的内容 112 | while ((temp = br.readLine()) != null) { 113 | buf = buf.append(System.getProperty("line.separator")); 114 | buf = buf.append(temp); 115 | } 116 | 117 | br.close(); 118 | FileOutputStream fos = new FileOutputStream(file); 119 | PrintWriter pw = new PrintWriter(fos); 120 | pw.write(buf.toString().toCharArray()); 121 | pw.flush(); 122 | pw.close(); 123 | } catch (IOException e) { 124 | e.printStackTrace(); 125 | } 126 | } 127 | } 128 | --------------------------------------------------------------------------------