Java对文本文件的增删查改

  • 文本文件
	private static List<String> readWordFromFile(String path) {
		List<String> words;
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(WordFilter.class.getClassLoader().getResourceAsStream(path)));
			words = new ArrayList<String>(1200);
			for (String buf = ""; (buf = br.readLine()) != null;) {
				if (buf == null || buf.trim().equals(""))
					continue;
				words.add(buf);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if (br != null)
					br.close();
			} catch (IOException e) {
			}
		}
		return words;
	}
	/**
	 *功能描述  获取不重复的敏感词列表
	 * @author FuHang
	 * @date 2019/8/23
	 */
	public static List<String> getSensitiveWords() {
		List<String> words = readWordFromFile("wd.txt");
		ArrayList<String> resultList = new ArrayList<String>();
		// 去除文件中的重复数据
		for (String item : words) {
			if (!resultList.contains(item)) {
				resultList.add(item);
			}
		}
		return resultList;
	}
	/**
	 *功能描述 修改敏感词列表
	 * @author FuHang
	 * @date 2019/8/23
	 */
	public static void change(String oldStr,String newStr){
		try {
			Resource resource = new ClassPathResource("wd.txt");
			File sourceFile =  resource.getFile();

//			WordFilter.class.getClassLoader().getResourceAsStream(path)
			RandomAccessFile raf = new RandomAccessFile(sourceFile, "rw");
			String line;
			while (null!=(line=raf.readLine())) {
				if(line.contains(oldStr)){
					String[] split = line.split(oldStr);
					raf.seek(split[0].length());
					raf.writeBytes(newStr);
					raf.writeBytes(split[1]);
				}
			}
			raf.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 *功能描述  添加
	 * @author FuHang
	 * @date 2019/8/23
	 */
	public static boolean addFile(String data) {
		RandomAccessFile rFile = null;
		try {
			Resource resource = new ClassPathResource("wd.txt");
			File sourceFile =  resource.getFile();
			rFile = new RandomAccessFile(sourceFile, "rw");
			long point = rFile.length();
			// 到达文件尾
			rFile.seek(point);
			rFile.writeBytes(data + "\r\n");
            /*
			 * rFile.writeUTF(data + "\r\n");
			 * rFile.writeInt(2);
             */
			rFile.close();
		} catch (Exception e) {
			return false;
		}
		return true;
	}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值