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();
			}
		}
		
		
	}

 

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