1、写入文件及读取文件内容
public static void main(String[] args) {
//写入文件
String rootPath = "D:\\";
FileUtil.makeDirs(rootPath + "test");
try{
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(rootPath+"test"+"\\"+"白.txt")),"utf-8"));
bw.write("最初的梦想,最终会到达");//在创建好的文件中写入模板的信息
bw.close();//关闭输出流
}catch(IOException e){
e.printStackTrace();
}
//读取文件
String demo = "D:\\test\\白.txt";
String content = readToString(demo);
System.out.println(content);
}
2、读取文件执行的方法
/**
* 读取本地文件
* <p><b>创建人:</b><br> 白 2019/7/30 12:42<br>
* <p><b>修改人:</b><br> 2019/7/30 12:42<br>
* <p><b>修改说明:</b><br> <br>
* @return
*/
public static String readToString(String fileName) {
String encoding = "UTF-8";
File file = new File(fileName);
Long filelength = file.length();
byte[] filecontent = new byte[filelength.intValue()];
try {
FileInputStream in = new FileInputStream(file);
in.read(filecontent);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
return new String(filecontent, encoding);
} catch (UnsupportedEncodingException e) {
System.err.println("The OS does not support " + encoding);
e.printStackTrace();
return null;
}
}
欢迎大家关注一下我的公众号!!