java深化——文件字节流与文件字符流

文件字节流:    

       FileInputStream/FileOutputStream
    
      FileInputStream通过字节的方式直接读取文件,适合读取所有类型的文件(图像、视频、文本文件等)。
     Java也提供了FileReader专门直接读取文本文件。

      FileOutputStream 通过字节的方式写数据到文件中,适合所有类型的文件。
    Java也提供了FileWriter专门写入文本文件。

           使用 FileInputStream (字节输入流)读取文件内容


        1) abstract int read( );      
        2) int read( byte b[ ] );  
        3) int read( byte b[ ], int off, int len );  
        4) int available( );  
        5) close( );

           使用 FileOutputStream (字节输出流)写内容到文件
        1) abstract void write( int b );  
        2) void write( byte b[ ] );  
        3) void write( byte b[ ], int off, int len );  
        4) void flush( );
        5) void close( );

public static void main(String[] args) throws IOException {
		//数据源与程序之间搭建通道
		FileInputStream fis = new FileInputStream(new File("E:\\test.txt"));
		//创建一个数组类型的中转站,便于一次读取全部数据,节省资源
		byte [] b=new byte[1024];
		int len=0;
		while((len=fis.read(b))!=-1) {
			System.out.println(new String(b,0,len));
		}
		fis.close();
	}

文件字符流:

Reader(字符输入流)/Writer(字符输出流)

    字符流一般用来操作纯文本

    使用 Reader(读出来) 读取文件内容
        1) int read( );  
        2) int read( char [ ]cbuf );  
        3) int read( char [ ]cbuf, int off, int len );  
        4) int available( );  
        5) close( );

    使用 Writer (写进去)写内容到文件
        1) void write( int c );  
        2) void write( char[]cbuf);   
        3) abstract void write( char [ ]cbuf, int off, int len );
        4) void write(String str);
        5) abstract void flush( );
        6) void close( );

public static void main(String[] args) {
		FileReader reader=null;
		try {
			reader = new FileReader("E:\\test.txt");
			/*  int i = 0;
				while((i=reader.read())!=-1) {
					System.out.println((char)i);   //有几个字节就得度几次
				}		*/
			char[] ch =new char[1024];
			int len=0;
			while((len=reader.read(ch))!=-1) {     //不管几个字节,只需读一次
				System.out.println(new String(ch,0,len));
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				reader.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
	}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章