读写txt文档

一、 工作中读写txt文件是一种很常用的方式,比如日志记录,当然需要有对应的解析脚本解析,然后得出我们需要的数据。本文只是简单地对文件读入和输出

1、文件读入,先判断文件是否存在,不存在则退出。然后对流进行封装,用一个BufferedReader读,每次一行,然后进行相应的处理。

/**
	 * 读txt
	 * @param path 文件路径
	 * @return
	 */
	public static Set<String> readTxt(String path) {
		BufferedReader br = null;
		Set<String> set = null;
		try {
			File file = new File(path);
			//判断文件是否存在
			if (file.exists()) {
			} else {
				System.out.println(path + "文件不存在!");
				return null;
			}
			//中文的时候要注意文件的编码
			InputStreamReader reader = new InputStreamReader(new FileInputStream(file), "utf-8");
			br = new BufferedReader(reader, 1024 * 1024);
			String line = "";
			set = new HashSet<String>();
			while ((line = br.readLine()) != null) {
//				对每行进行处理,此处只是简单的打印
//				System.out.println(line);
				set.add(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null) {
					br.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return set;
	}


2、写文件,把处理好的数据存入容器,然后指定路径输出

/**
	 * 写txt文件
	 * @param col需要写入文件的数据
	 * @param path写入文件路径
	 */
	public static void writeTxt(Collection<String> col, String path) {
		try {
			File f = new File(path);
			if (!f.exists()) {
				//文件不存在则建立一个
				f.createNewFile();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter(new FileWriter(path));
			if (col.size() != 0) {
				Iterator<String> iter = col.iterator();
				while (iter.hasNext()) {
					String pid = (String) iter.next();
					bw.write(pid + "\r\n");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				bw.flush();
				bw.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}


 

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值