写入
OutputStreamWriter----->FileOutputStream
@Test
public void writeF() throws IOException{
File file=new File("C:/Users/Administrator/Desktop/note/实例创建.txt");
if(!file.exists())
file.createNewFile();
else{
System.err.println("[实例创建.txt]文件已经存在\n路径为 "+file.getPath());
System.exit(0);
}
OutputStreamWriter os= new OutputStreamWriter(new FileOutputStream(file),"utf-8"); //创建编码转换流(OSW)
os.write("主人你好!!!\r\n我这么幸运!!!!能被主人创建出来,一次新生好开心!!!!");
os.close();
}
读取
BufferedReader----->InputStreamReader----->FileInputStream
@Test
public void readF() throws Exception, Exception{
File file=new File("C:/Users/Administrator/Desktop/note/实例创建.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(file),"utf-8"));
String string="";
while ((string=br.readLine())!=null) { //读取方法一:br.readLine())!=null
System.out.println(string);
}
// while (br.ready()) {
// System.out.println(br.readLine()); //读取方法二:br.ready()为true时表示未读完
// }
br.close();
}
补充
RandomAccessFile类
可以跳转到文件的任意位置处读写数据
写文件
RandomAccessFile wf=new RandomAccessFile(new File("a.txt"),"rw" );
wf.writeUTF("Tom吃了我一年的apple。我很亏!!!");
wf.close();
写文件读文件都要重新实例化RandomAccessFile对象
读取文件
RandomAccessFile rf=new RandomAccessFile(new File("a.txt"),"rw" );
System.out.println(rf.readUTF());
rf.close();
执行结果: