文件讀寫概要

package com.li.javase;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;

public class TestArray {
	
	//字節流讀寫
	public static void file1(){
		
		File fl1 = new File("ccc.gif");
		
		File fl2 = new File("bbb.gif");
		try{
			InputStream is = new FileInputStream(fl2);
			OutputStream os = new FileOutputStream(fl1);
			int len = 0;
			byte [] b1 = new byte[1024];
			while((len = is.read(b1))!=-1){
				os.write(b1, 0, len);
			}
			is.close();
			os.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	//字節流寫
	public static void file2(){
		
		File fl1 = new File("str.txt");
		String s = "this is a String!這是字符串哦 ";
		try {
			OutputStream os = new FileOutputStream(fl1);
			byte [] b = s.getBytes();
			os.write(b);
			os.close();
		} catch (Exception e) {
		}
	}
	
	//字符流寫
	public static void file3(){
		File fl1 = new File("str.txt");
		String s = "this is a String!這是字符串哦ddddddd ";
		try {
			
			Writer writer = new FileWriter(fl1);
			//Reader reader = new FileReader(fl1);
			char [] c = s.toCharArray();
			writer.write(c);
			writer.close();
			
		} catch (Exception e) {
		}
	}
	/**
	 * 在Java中IO操作也是有相應步驟的,以文件操作爲例,主要的操作流程如下:
		1 使用File類打開一個文件
		2 通過字節流或字符流的子類,指定輸出的位置
		3 進行讀/寫操作
		4 關閉輸入/輸出
		
		字節流抽象類:
			InputStream/OutputStream
			根據需要選擇子類進行文件讀寫即可
		
		字符流抽象類:
			Writer/Reader
			同樣根據需要選擇子類進行文件讀寫即可
			
		一般中文由字符流處理,二進制文件由字節流處理
	 */
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		//file1();
		//file2();
		file3();

	}

}


發佈了28 篇原創文章 · 獲贊 31 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章