读取txt文本里的数据

用来读取text文本中的数据(分两种方式读取)

1.只要没读完,不断的读取

public static String readFile(File file) {
	try {
		FileInputStream fileInputStream = new FileInputStream(file);
		// 把每次读取的内容写入到内存中,然后从内存中获取
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte [] buffer = new byte [1024];
		int len = 0;
		// 只要没读完,不断的读取
		while ((len=fileInputStream.read(buffer))!=-1)
		{
			outputStream.write(buffer, 0, len);
		}
		// 得到内存中写入的所有数据
		byte [] data = outputStream.toByteArray();
		fileInputStream.close();
		return new String(data,"utf-8"); //以GBK(什么编码格式)方式转
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return null;
}

2.一行一行的读取txt文本中的数据

public static String readFile(File file) {
	StringBuilder sb = new StringBuilder();//相当于一个容器,可以进行添加和删除操作
		try {
			FileInputStream fileInputStream = new FileInputStream(file);
			InputStreamReader isr = new InputStreamReader(fileInputStream,"utf-8");//这里的编码方式需要和自己txt文本的编码方式一样,要不然读出来的数据会是乱码
			BufferedReader br = new BufferedReader(isr);
			String line="";
			//一行一行的读取,当不为空是把值添加到StringBuilder中
			while((line=br.readLine())!=null)
			{
				sb.append(line+"\r\n");
			}
			br.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	return sb.toString();
}
##  测试
public static void main(String[] args) {
	// TODO Auto-generated method stub
	String content =readFile(new File("D:\\aaa.txt"));
	System.out.print("content:" + content);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值