java输入输出流处理

来源:互联网 发布:linux 启动命令 编辑:程序博客网 时间:2024/06/09 21:01

一.理解数据流

   数据流:是一组有顺序,有起点和终点的字节集合,是对输入和输出的抽象.
  数据流分为输入流(InputStream)跟输出流(OutStream).前者只能读不能写,后者只能写不能读
 

二.字节流与字符流

java定义了两种类型的流:字节流与字符流.字节流是为了处理字节的输入与输出提供了方便.字符流是为了处理字符的输入与输出提供了方便.
注意:在最底层,所有的输入与输出都是字节形式.基于字符的流只为了处理字符更加有效而提供的方法.
字节流的分类图如下:
字节输入流

字节输出流



字符输入流:

字符输出流:


三.file类

File类是IO包中唯一代表磁盘文件本身的对象。通过File来创建,删除,重命名文件。File类对象的主要作用就是用来获取文本本身的一些信息。如文本的所在的目录,文件的长度,读写权限等等。(有的需要记忆,比如isFile(),isDirectory(),exits();有的了解即可。使用的时候查看API)
常见的方法:
new File("路径名").mkdir();创建一个文件夹
new File("文件名").createNewFile();创建一个新文件
file.delete();删除文件
isDirectory();判断是否为目录
isFile();判断是否为文件
file.getAbsoluteFile();返回绝对文件名
file.getAbsolutePath();返回绝对路径

四.操作演示代码

要求一:将文件夹一中的文档的内容复制到文件夹二中的文档中

public class Test {public static void main(String[] args) {File f=new File("G:\\文件夹1");f.mkdir();File file=new File("G:\\文件夹1\\文档1.txt");//创建文件夹1中的文档try {file.createNewFile();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();System.out.println("创建失败");}String s1="大家好";try {FileWriter fw=new FileWriter(file);fw.write(s1);fw.close();} catch (IOException e) {System.out.println("写入失败");e.printStackTrace();}File f2=new File("G:\\文件夹2");f2.mkdir();File file2=new File("G:\\文件夹2\\文档2.txt");//创建文件夹2中的文档成功try {FileInputStream fis=new FileInputStream(file);//用来读的文件FileOutputStream fos=new FileOutputStream(file2);//用来写的文件byte[] bytes=new byte[1024];//用来每次读的字节数 
                int length;while ((length=fis.read(bytes))!=-1) {fos.write(bytes,0,length);}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

要求二:将以下的语句{}里面的内容替换成具体的名字
您好,我的名字是{name},我是一只{type}.我的主人是{master}
比如:我的名字是欧欧,我是一只狗狗,我的主人是张伟
public class Test2 {/** * @param args * @throws IOException */public static void main(String[] args) throws IOException {// TODO Auto-generated method stubString str = "您好,我的名字是{name},我是一只{type}.我的主人是{master}。";String str1 = str.replace("{name}", "欧欧");String str2 = str1.replace("{type}", "狗狗");String str3 = str2.replace("{master}", "李伟");System.out.println(str3);FileWriter fw = null;try {fw = new FileWriter(new File("g:\\PET\\pet.txt"));fw.write(str);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {fw.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}Writer w = new FileWriter("g:\\PET\\pet.txt",false);
                //这里为true,表示保留之前的语句,为false 不保留原来的内容w.write(str3);w.close();}}

字节流与字符流的区别:
 操作字节流本身不会用到缓冲区,是文件本身直接操作的,而字符流操作时用到了缓冲区,如果我们在操作字符流,没关闭流,我们写入的数据是无法保存的.所以一定要关闭流

序列化:通过对象流将java的类对象写入到文件中
反序列化:通过对象流从文件中读取类对象的过程

原创粉丝点击