zoukankan      html  css  js  c++  java
  • Java基础知识回顾之六 ----- IO流

    前言

    上一篇文章中,回顾了Java的多线程。而在本篇文章中主要介绍Java IO的相关知识。

    IO的介绍

    什么是IO?

    IO的名称又来是Input与Output的缩写,也就是输入流和输出流。输入流用于从源读取数据,输出流用于向目标写数据。

    可以从下列示例图来了解IO流:

    IO流使用

    IO流对文件的操作主要分为字符流和字节流。

    字符流

    字符流有两个抽象类:WriterReader类。
    其对应子类FileWriterFileReader可实现文件的读写操作。
    BufferedWriterBufferedReader能够提供缓冲区功能,用以提高效率。

    我记得在开始学习Java不久的时候, 在教程中会使用 字符流来进行字符的读取和写入。比较常见的就是,运行一个main方法,然后再控制台输入字符,获取输入的字符做一些逻辑控制之类。
    例如: 在控制台输入字符,输入quit退出,输入其它的字符打印。

    代码示例:

    	public static void main(String[] args)  {
    		try {
    			test();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    
    	private static void test() throws IOException {
    		  String str;
    		    // 使用 System.in 创建 BufferedReader 
    		    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    		    System.out.println("输入字符, 输入 'quit' 退出。");
    		    // 读取字符
    		    do {
    		       str=br.readLine();
    		       System.out.println("您输入的字符是:"+str);
    		    } while(!str.equals("quit"));
    			 br.close();
    	}
    

    然后我们输入 helloquit
    结果如下:

    输入字符, 输入 'quit' 退出。
    hello
    您输入的字符是:hello
    您输入的字符是:
    quit
    您输入的字符是:quit
    

    通过上述示例我们可以简单的了解下了字符流。
    一般来说,我们主要用字符流的情况是读写文件,大部分也是文本文件,比如.txt后缀的。这里我们也顺便介绍下如何使用。

    代码示例:

    	/**
    	 *
    	 * 写入和读取文件
    	 * @throws IOException
    	 */
    	private static void test2() throws IOException {
    		//创建要操作的文件路径和名称  
            String path ="E:/test/hello.txt";
            String str="hello world";
            FileWriter fw = new FileWriter(path);  
            fw.write(str);  
            fw.close();  
            
            FileReader fr = new FileReader(path);  
            StringBuffer sb=new StringBuffer();
      		while(fr.ready()){
      			sb.append((char)fr.read());
      		}
            System.out.println("输出:"+sb.toString());
            fr.close();
    	}
    
    

    注:如果在不同的系统上运行,可以使用 File.separator方法,该方法表示系统的分隔符。

    输出结果:

    输出:hello word
    

    上述代码示例中,我们使用FileWriterFileReader 这两个类对文件进行读写,虽然可以实现字符的写入和读取,但是效率并不高,因为是对磁盘的直接读写。一般对于文件的读写,我们会使用缓冲。使用缓冲的好处就像 倒垃圾一样,将垃圾进行整理堆积,然后到了一定的规模在丢弃,而不是有一点垃圾就倒一次。

    那么在上述的代码中加上BufferedWriterBufferedReader类来进行缓冲。

    代码示例:

    	/**
    	 * 写入和读取文件
    	 * @throws IOException
    	 */
    	private static void test3() throws IOException {
    		//创建要操作的文件路径和名称  
            String path ="E:/test/hello.txt";
            String str="你好!";
            FileWriter fw = new FileWriter(path);  
            BufferedWriter bw=new BufferedWriter(fw);
            bw.write(str);  
            bw.close();
            fw.close();  
            
            FileReader fr = new FileReader(path);  
            BufferedReader br=new BufferedReader(fr);
            StringBuffer sb=new StringBuffer();
      		while(br.ready()){
      			sb.append((char)br.read());
      		}
            System.out.println("输出:"+sb.toString());
            br.close();
            fr.close();
    	}
    

    注:需要注意的是关闭的顺序,先关闭缓冲,再关闭文件。

    字节流

    字节流也有两个抽象类:InputStreamOutputStream类。
    其对应子类有FileInputStreamFileOutputStream实现文件读写操作。
    BufferedInputStreamBufferedOutputStream提供缓冲区功能

    字节流也能对文本进行读取,但是它的主要使用的场景是读取无法直接获取文本信息的二进制文件,比如音乐文件、视频文件、图片文件等等。
    这里我们依旧对文件进行读取和写入,不过我们把之前写入到hello.txt文件的内容加上 '你好' 写入到新的文件中。由于这里使用的了中文,所以需要设置相应的编码。

    代码示例:

     /**
    	 * 创建一个文件并读取记录 
    	 * @throws IOException
    	 */
    	private static void test4() throws IOException {
    		String path="E:/test/hello.txt";
    		String path2="E:/test/你好.txt";
    		String str="你好!";
    		//从文件读取数据
    		InputStream input = new FileInputStream(path);
    		InputStreamReader reader = new InputStreamReader(input, "UTF-8");
    	    StringBuffer sb=new StringBuffer();
    		while(reader.ready()){
    			sb.append((char)reader.read());
    		}
    		
    		input.close();
    		reader.close();
    		
    		//创建一个文件并向文件中写数据
    		OutputStream output = new FileOutputStream(path2);
    		OutputStreamWriter writer = new OutputStreamWriter(output, "UTF-8");
    		writer.write(sb+str);
    		
    		writer.close();
    		output.close();
    		
    		//从文件读取数据
    		InputStream input2 = new FileInputStream(path2);
    		InputStreamReader reader2 = new InputStreamReader(input2, "UTF-8");
    	    StringBuffer sb2=new StringBuffer();
    		while(reader2.ready()){
    			sb2.append((char)reader2.read());
    		}
    		System.out.println("输出:"+sb2);
    		input2.close();
    		reader2.close();
    	}	
    

    结果:

    	输出:hello world你好!
    

    可以看到结果符合我们的预期。

    File

    学习IO流中,我们也会接触File类。
    File类中主要是对文件夹的一些操作。比如,文件夹的创建、删除、查看等等。
    这里我们就简单的介绍下File类的相关使用,还是使用代码配合注释来进行说明。

    代码示例:

    private static void test5() throws IOException {
    		String path="E:/test/test2";
    		String path2="E:/test/test3/test3";
    		String path3="E:/test/test2/test2.txt";
    		File f = new File(path);
    		File f2 = new File(path2);
    		File f3 = new File(path3);
    		//创建文件夹
    		System.out.println("="+f.mkdir());
    		//创建文件夹和所有父文件夹
    		System.out.println("=="+f2.mkdirs());
    		//创建一个文本
    		System.out.println("==="+f3.createNewFile());
    		//获取名称
    		System.out.println("==="+f3.getName());
    		//获取父级名称
    		System.out.println("==="+f3.getParent());
    		//获取当前路径
    		System.out.println("==="+f3.getPath());
    		//判断是否是目录
    		System.out.println("=="+f2.isDirectory());
    		System.out.println("==="+f3.isDirectory());
    		//删除该文件
    		System.out.println("==="+f3.delete());	
    }	
    

    输出结果:

    =true
    ==true
    ===true
    ===test2.txt
    ===E:	est	est2
    ===E:	est	est2	est2.txt
    ==true
    ===false
    ===true
    

    关于File类的相关只是简单的介绍了下,具体的使用还需要配置实际的场景。需要注意的是,在进行文件创建和删除的时候,需要先判断是否存在,否则将抛出异常。

    其它

    到此,本文就结束了,谢谢阅读!欢迎留言和点赞,你的支持是我写作最大的动力!

    版权声明:
    作者:虚无境
    博客园出处:http://www.cnblogs.com/xuwujing
    CSDN出处:http://blog.csdn.net/qazwsxpcm    
    个人博客出处:http://www.panchengming.com

  • 相关阅读:
    shell tr命令的使用
    linux find prune排除某目录或文件
    在vue中使用axios发送post请求,参数方式
    webpack官网demo起步中遇到的问题
    css中盒子模型与box-sizing属性
    jquery获得 url的变量
    17-js观察者模式
    基于Jquery ui 可复用的酒店 web页面选择入住日期插件
    webkit浏览器下改变滚动条样式
    用户登录时,禁止chrome提示用户保存密码
  • 原文地址:https://www.cnblogs.com/xuwujing/p/9191546.html
Copyright © 2011-2022 走看看