java 写文件和读文件操作

1.简介

最近工作中碰到文件读写的操作,写个文档总结一下。

2.写内容到文件

主要涉及到文件的创建,String字符串或者byte[]字节数组写入文件,代码如下:

String strXml = new String("大吉大利,今晚吃鸡");
byte[] bXML = strXml.getBytes();
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
    File dir = new File(System.getProperty("user.dir") + "//" + "textdir");
    boolean isDir = dir.isDirectory();
    if (!isDir) {
    	// 目录不存在则先建目录
        try {
        	dir.mkdirs();
        } catch (Exception e) {
        	e.printStackTrace();
        }
	}
	file = new File(dir.getPath() +"//"+ "aaa.txt");
	fos = new FileOutputStream(file);
	bos = new BufferedOutputStream(fos);
	bos.write(bXML);
	bos.close();
} catch (Exception e) {
	e.printStackTrace();
}

即可在该项目根目录下创建textdir文件夹以及aaa.txt文件,“大吉大利,今晚吃鸡"成功写入到文件中。

3.读文件内容

将文件中的内容读到byte数组或String字符串中。

byte[] bXML = new byte[200];
BufferedInputStream bis = null;
FileInputStream fis = null;
File file = new File(System.getProperty("user.dir") + "//" + "textdir//"+"aaa.txt");
try {
    fis = new FileInputStream(file);
    bis = new BufferedInputStream(fis);
    try {
        bis.read(bXML);
        bis.close();
    } catch (IOException e) {
    	e.printStackTrace();
    }
    try {
    	strXml = new String(bXML,"UTF-8"); // 以utf-8编码格式转换
    } catch (UnsupportedEncodingException e) {
    	e.printStackTrace();
    }
    System.out.println(strXml);
} catch (FileNotFoundException e) {
	e.printStackTrace();
}

这样就可以成功将txt中的内容读入到String字符串中。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值