目录
书接上文
FileWriter
package ljy;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Hellojave {
public static void main(String[] args) {
File f=new File("word.txt");
FileWriter fw=null;
try {
fw=new FileWriter(f);
String str="南昌航空大学";
fw.write(str);
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}finally {
if(fw!=null) {
try {
fw.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}
}
还有个参数和字节流的out差不多
FileReader
也不好说什么;
要注意的就是字节流用的是byte,字符流是char
所有代码:
package ljy;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Hellojave {
public static void main(String[] args) {
File f=new File("word.txt");
// FileWriter fw=null;
// try {
// fw=new FileWriter(f,false);//覆盖
//
// String str="南昌航空大学";
// fw.write(str);
// } catch (IOException e) {
// // TODO 自动生成的 catch 块
// e.printStackTrace();
// }finally {
// if(fw!=null) {
// try {
// fw.close();
// } catch (IOException e) {
// // TODO 自动生成的 catch 块
// e.printStackTrace();
// }
// }
// }
FileReader fr=null;
try {
fr=new FileReader(f);
char ch[]=new char[1024];//缓冲区
int count=0;//已经读出的字符数
while((count=fr.read(ch))!=-1) {//循环读取文件数据,直到使用字符读完
System.out.println("文件中的内容为:"+new String(ch,0,count));
}
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}finally {
if(fr!=null) {
try {
fr.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}
}