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字符串中。