目录
(1)实例一个File对象创建新的文件,通过FileWriter对文件写入,在使用FileReader对文件读取。
(2)FileOutputStream写入,FileInputStream读取。
1、简介
(1)java io 是表示数据输入输出操作。IO是int\out缩写,Stream表示流。
(2)按照功能可分为输入流、输出流。
(3)按单元分类有字节流、字符流。
InputStream:字节输入流;
OutputStream:字节输出流;
FileWriter:字符输出流;
FileReader:字符输入流;
(4)应用场景:当我们需要对数据流进行解析处理时,可采用字符流;当处理文件是音频或者视频文件时应该采用字节流。字符流底层实现仍是字节流
2、应用实例
(1)实例一个File对象创建新的文件,通过FileWriter对文件写入,在使用FileReader对文件读取。
public static void main(String[] args) throws IOException { String string="D:\\txt_file"+"\\"+new SimpleDateFormat("YYYY-MM-dd hh-mm-ss").format(new Date())+".txt"; File file=new File(string); if(!file.exists()){ //创建新的文件 boolean flag=file.createNewFile(); System.out.println(flag?"yes":"no"); } FileWriter writer=new FileWriter(string,true); writer.write("第一条记录\n"); //追加文件内容 writer.close(); FileReader fileReader=new FileReader(string); char[] buf=new char[1024]; fileReader.read(buf); //读取文件 System.out.println(new String(buf,0,1024)); fileReader.close(); }
(2)FileOutputStream写入,FileInputStream读取。
public static void the2() throws IOException { String string="D:\\txt_file"+"\\"+new SimpleDateFormat("YYYY-MM-dd hh-mm-ss").format(new Date())+".txt"; FileOutputStream fileOutputStream=new FileOutputStream(string); byte[] bytes = new String("字节试试").getBytes("utf-8"); fileOutputStream.write(bytes); FileInputStream fileInputStream=new FileInputStream(string); byte[] read=new byte[1024]; fileInputStream.read(read); System.out.println(new String(read)); }
至此完毕!