ファイル入出力バイトストリーム


詳細
FileInputStream FileOutputStreamの使い方まとめ
 
byte配列でコンテンツを保存する.小ファイルの読み取り書き込みに適した操作
 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 
 * @author hb
 */
public class FileIo {
	/**
	 *     InputStream     
	 *     OutputStream    
	 */
	
	public static void main(String[] args) {
		//String str="        ";
//		String Path="d:\\ISO.vdi";//        available(),zip                   。         
		
		String Path = "d:\\1.docx";
		String Path1 = "d:\\2.txt";
		byte[] bf={-42,-48,-60,-49,-63,-42,-46,-75,-65,-58,-68,-68,-76,-13,-47,-89};//           .
		File f= new File(Path);
		File f1= new File(Path1);
		byte b[]=reader(f);		
		writter(f1,b);
	}
	
	public static void writter(File f,byte bs[]){
		if(!f.exists()){
			try {
				f.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		try {
			FileOutputStream fos = new FileOutputStream(f,true);//       	
//			FileOutputStream fos = new FileOutputStream(f);//    
	//**********************    1***********		
//			byte[] bs = str.getBytes();
//			fos.write(bf);
			
			//  2:           , for   。***********
			for(byte b:bs){
				
				fos.write(b);	
				
			}

			//      ,          
				fos.flush();
				fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
	}
	
	public static byte[] reader(File f){
		try {
			FileInputStream fis = new FileInputStream(f);
			int len = fis.available();
			byte [] bs=new byte[len];
			
			
//*********************************************************//
			
//			while(len>0){			
//			int b= fis.read();
//			System.out.println(b);
//			System.out.println(fis.available());
//			len=fis.available();
//		}
			
//*********************************************************//

//			int i=0;
//			int b= fis.read();
//			while(b!=-1){
//				bs[i]=(byte)b;
//				i++;
//				b= fis.read();
//				
//				
//			}
			
//*********************************************************//
			
			fis.read(bs);
			
			
			fis.close();
			String str= new String(bs);
			System.out.println(str);
			return bs;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
		
	}
	
	
}