JavaのI/O(1)

2481 ワード

ターゲット:
1.I/O操作の目標。
2.I/O分類
3.ファイルの読み込みとファイルの書き込みの方法。
 
ストリームとは、データソースとプログラムとの間のチャネルのことです。
 
I/Oの流れ:
  [ファイル]     Input                   Output       [ファイル]
  [キーボード]     ------>   Javaプログラム  ------->        [スクリーン]
  [ネットワーク]                                                    [ネットワーク]
 
-----------------------------------------
 
第1の分類:1.入力ストリーム2.出力ストリーム
第2の分類:1.バイトストリーム2.文字ストリーム
第3の分類:1.ノードフロー2.処理フロー
 
-------------------
 
バイトストリームのコアクラス
                          extens
InputStream   <------------  FileInputStream
                         extens
OutputStream<-------------   FileOutputStream
 
------------------------
 
InputStream:
         int read(byte[]buffer、int offset、int length)
OutputStream:
         void write(byte[]buffer、int offset、int length)
 
Stringオブジェクトを呼び出すtring()メソッドは、この文字列の先頭のスペースと空の文字を削除します。
public String trim()
 Copies this string removing white space characters from the begining and end of the string.
 
//   
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;

class Test{
	public static void main(String args []){
		//        
		FileInputStream fis = null;
		//        
		FileOutputStream fos = null;
		try{
			//          
			fis = new FileInputStream("m:/src/from.txt");
		 	
			//          
			fos = new FileOutputStream("m:/src/to.txt");
			
			//        
			byte [] buffer = new byte[1024];
			while (true) {				
				//        read  ,    
				int temp = fis.read(buffer, 0, buffer.length);
				if (temp == -1) {
					break;
				}
				fos.write(buffer, 0, temp);
			}	
			
//			String s = new String(buffer);	
			//Copies this string removing white space characters
			//from the beginning and end of the string.
//			s = s.trim(); 
//			System.out.println(s);						
		}
		catch (Exception e) {
			System.out.println(e);
		}
		finally {
			try{
				fis.close();
				fos.close();
			}
			catch (Exception e) {
				System.out.println(e);
			}
		}
	}
}