java 读取与写入文件(字符流)
java 读取与写入文件
public static void writeFile(){
String strPath = "H:\\bbb\\aa\\tt.txt";
try {
File file = new File(strPath);
File fileParent = file.getParentFile();
if(!fileParent.exists()){
fileParent.mkdirs();
}
//此判断可以不要
if(!file.exists()){
file.createNewFile();
}
BufferedWriter out=new BufferedWriter(new FileWriter(file));
out.write("wo shi");
out.newLine();
out.write("yin");
out.newLine();
out.write("ye ye");
out.close();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public static void readFile(){
String strPath = "H:\\bbb\\aa\\tt.txt";
BufferedReader in = null;
try {
in=new BufferedReader(new FileReader(strPath));
String line = null;
try {
while ((line = in.readLine()) !=null){
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
//关闭BufferedReader
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

