1. 程式人生 > >java IO流練習

java IO流練習

package practice.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
/**
 * 
 * @author ljz
 *     ******************
 *        *位元組流           *字元流       
 *  讀    InputStream      Reader
 *  寫    OutputSrtream    Writer
 * 位元組流和字元流的差別
 * 1、  位元組流需要先將String轉換成byte陣列然後才能使用流進行寫,寫的時候也是寫入byte陣列。
 *      字元流可直接對string進行寫,讀的時候讀入char陣列
 * 2、  位元組流不使用快取
 *      字元流使用快取,可以使用flush將快取中的內容寫入硬碟
 */
public class IOPra { public static void main(String[] args){ IOPra p = new IOPra(); try { p.zijiePra(); p.zifuPra(); p.zijieInPra(); p.zifuInPra(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public
void zijiePra() throws Exception{ File file = new File(".." + File.separator + "位元組.txt"); file.createNewFile(); String str = "io practice !"; byte[] by = str.getBytes(); OutputStream os = new FileOutputStream(file); os.write(by); os.close(); System.out.println("finish"
); } public void zifuPra() throws Exception{ File file = new File(".." + File.separator + "字元.txt"); file.createNewFile(); String str = "io practice !"; Writer writer = new FileWriter(file); writer.write(str); //writer.flush(); writer.close(); System.out.println("finish"); } public void zijieInPra() throws Exception{ File file = new File(".." + File.separator + "位元組.txt"); InputStream is = new FileInputStream(file); byte[] by = new byte[(int) file.length()]; int len = is.read(by); System.out.println(len + ":" + new String(by)); is.close(); } public void zifuInPra() throws Exception{ File file = new File(".." + File.separator + "字元.txt"); Reader re = new FileReader(file); char[] ch = new char[(int)file.length()]; int len = re.read(ch); System.out.println(len + ":" + new String(ch)); re.close(); } public void copyFile() throws Exception{ File souFile = new File(".." + File.separator + "位元組.txt"); File desFile = new File("D:" + File.separator + "copy位元組.txt"); if(desFile.exists()) desFile.createNewFile(); byte[] by = new byte[(int)souFile.length()]; InputStream is = new FileInputStream(souFile); is.read(by); OutputStream os = new FileOutputStream(desFile); os.write(by); is.close(); os.close(); } }