Java位元組流和字元流執行個體__IO流

來源:互聯網
上載者:User

1.基本概念

按資料類型分:Java有位元組流和字元流兩種:

位元組流:InputStream/OutputStream

字元流:Reader/Writer

位元組流讀取的時候,讀到一個位元組就返回一個位元組;

字元流使用了位元組流讀到一個或多個位元組(中文對應的位元組是兩個,UTF-8碼錶中是3個)時,先去查指定的編碼錶,將查到的字元返回。


2.常用子類

位元組流都是以InputStream/OutputStream/Stream結尾,InputStream/OutputStream前面代表這個流的作用,它們都繼承了InputStream/OutputStream,

比如FileInputStream/FileInputStream表示操作檔案內容的位元組流,PrintStream表示用于格式化列印的位元組流;

字元流都是以Reader/Writer結尾,Reader/Writer前面代表這個流的作用,它們都繼承了Reader/Writer,

比如FileReader/FileWriter表示操作檔案內容的字元流,PrintWriter表示用于格式化列印的字元流。


2.使用場合

位元組流可以處理所有類型資料,如圖片、MP3等;

字元流只能處理字元資料。


下面是一個使用位元組流和字元流執行個體:


FileIO.java檔案:

package com.swsx.io;import java.io.File;/** * 用於檔案輸入輸出操作的介面 * @author Administrator * */public interface FileIO {String CLASS_PATH = System.getProperty("java.class.path") + File.separator;/** * 分行符號 */String LINE_SEPARATOR = System.getProperty("line.separator");/** * 建立一個檔案 * @param fileName * @return */boolean createFile(String fileName);/** * 刪除一個檔案 * @param fileName * @return */boolean deleteFile(String fileName);/** * 將內容寫入到檔案中 * @param fileName * @param content */void writeFile(String fileName, String content);/** * 將內容寫入到檔案中 * @param fileName * @param content * @param append 內是否追加 */ void writeFile(String fileName, String content, boolean append);  /** * 讀檔案中的內容 * @param fileName * @return */ String readFile(String fileName);}

AbstractFileIO.java檔案:

package com.swsx.io;import java.io.File;import java.io.IOException;/** * 實現FileIO的抽象類別 * @author Administrator * */public abstract class AbstractFileIO implements FileIO {public AbstractFileIO() {// TODO Auto-generated constructor stub}@Overridepublic boolean createFile(String fileName) {// TODO Auto-generated method stubif(fileName != null && !fileName.equals("")){File file = new File(CLASS_PATH + fileName);try {return file.createNewFile();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return false;}@Overridepublic boolean deleteFile(String fileName) {// TODO Auto-generated method stubif(fileName != null && !fileName.equals("")){File file = new File(CLASS_PATH + fileName);return file.delete();}return false;}@Overridepublic void writeFile(String fileName, String content) {// TODO Auto-generated method stubwriteFile(fileName, content, false);}@Overridepublic abstract void writeFile(String fileName, String content, boolean append);@Overridepublic abstract String readFile(String fileName);}

FileStreamIO.java檔案:

package com.swsx.io;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.PrintStream;/** * 檔案輸入輸出操作位元組流實現 * @author Administrator * */public class FileStreamIO extends AbstractFileIO {public FileStreamIO() {super();// TODO Auto-generated constructor stub}@Overridepublic void writeFile(String fileName, String content, boolean append){if(fileName != null && content != null && !fileName.equals("")){byte[] b = content.getBytes();OutputStream output = null;try {output = new FileOutputStream(CLASS_PATH + fileName, append);output.write(b);} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{if(output != null){try {output.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}//方法一:使用一個事先定好長度的位元組數組儲存全部檔案內容(可能溢出)//@Override//public String readFile(String fileName){//if(fileName != null && !fileName.equals("")){//File file = new File(CLASS_PATH + fileName);//InputStream input = null;//byte[] b = new byte[1024];//檔案內容全部讀到這裡//try {//input = new FileInputStream(file);//int temp = 0;//int count = 0;//while((temp = input.read()) != -1){//b[count++] = (byte)temp;//檔案過大時,可能會溢出//}//return new String(b);//} catch (FileNotFoundException e) {//// TODO Auto-generated catch block//e.printStackTrace();//} catch (IOException e) {//// TODO Auto-generated catch block//e.printStackTrace();//}finally{//if(input != null){//try {//input.close();//} catch (IOException e) {//// TODO Auto-generated catch block//e.printStackTrace();//}//}//}//}//return null;//}//方法二:使用ByteArrayOutputStream產生一個隱藏檔內容的位元組數組(可以避免內容溢出)@Overridepublic String readFile(String fileName){if(fileName != null && !fileName.equals("")){File file = new File(CLASS_PATH + fileName);InputStream input = null;//只是一個緩衝區  檔案全部內容讀到ByteArrayOutputStream中byte[] b = new byte[16];ByteArrayOutputStream out = new ByteArrayOutputStream();try {input = new FileInputStream(file);int len = 0;while((len = input.read(b)) != -1){out.write(b, 0, len);//ByteArrayOutputStream不會溢出}return new String(out.toByteArray());//將ByteArrayOutputStream中的內容轉化為位元組數組} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{if(input != null){try {input.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}return null;}/** * 格式化寫檔案 * @param fileName * @param append * @param format * @param args */public static void PrintFile(String fileName, boolean append, String format, Object...args){if(fileName != null && format != null && !fileName.equals("")){PrintStream pt = null;try {pt =new PrintStream(new FileOutputStream(CLASS_PATH + fileName, append));pt.printf(format, args);} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{if(pt != null){pt.close();}}}}}

FileCharacterIO.java檔案:

package com.swsx.io;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.Reader;import java.io.Writer;/** * 檔案輸入輸出操作字元流實現 * @author Administrator * */public class FileCharacterIO extends AbstractFileIO {public FileCharacterIO() {super();// TODO Auto-generated constructor stub}@Overridepublic void writeFile(String fileName, String content, boolean append) {// TODO Auto-generated method stubif(fileName != null && content != null && !fileName.equals("")){Writer out = null;try {out = new FileWriter(CLASS_PATH + fileName, append);out.write(content);} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{if(out != null){try {out.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}//方法一:使用一個事先定好長度的字元數組儲存全部檔案內容(可能溢出)//@Override//public String readFile(String fileName) {//// TODO Auto-generated method stub//if(fileName != null && !fileName.equals("")){//File file = new File(CLASS_PATH + fileName);//Reader in = null;//char[] c = new char[1024];//檔案內容全部讀到這裡//try {//in = new FileReader(file);//int temp = 0;//int count = 0;//while((temp = in.read()) != -1){//c[count++] = (char)temp;//檔案過大時,可能會溢出//}////return new String(c);//} catch (FileNotFoundException e) {//// TODO Auto-generated catch block//e.printStackTrace();//} catch (IOException e) {//// TODO Auto-generated catch block//e.printStackTrace();//}finally{//if(in != null){//try {//in.close();//} catch (IOException e) {//// TODO Auto-generated catch block//e.printStackTrace();//}//}//}//}//return null;//}//方法二:使用StringBuffer或StringBuilder隱藏檔內容(可以避免內容溢出)@Overridepublic String readFile(String fileName) {// TODO Auto-generated method stubif(fileName != null && !fileName.equals("")){File file = new File(CLASS_PATH + fileName);Reader in = null;//只是一個緩衝區  檔案全部內容讀到StringBuffer或StringBuilder中char[] c = new char[16];//StringBuffer或StringBuilder隱藏檔內容StringBuffer strBuffer = new StringBuffer();try {in = new FileReader(file);int len = 0;while((len = in.read(c)) != -1){strBuffer.append(c, 0, len);//不會溢出}return strBuffer.toString();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{if(in != null){try {in.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}return null;}}

TestFileIO.java檔案:

package com.swsx.io;public class TestFileIO {public static void main(String[] agrs){    FileIO fileIO = new FileCharacterIO();String fileName = "test1.txt";if(fileIO.createFile(fileName)){System.out.println("success");}String content = "你好!" + FileIO.LINE_SEPARATOR + "hello" + FileIO.LINE_SEPARATOR;fileIO.writeFile(fileName,content);FileStreamIO.PrintFile(fileName,true, "姓名:%s 年齡:%d%s", "張三", 3, FileIO.LINE_SEPARATOR);System.out.println(fileIO.readFile(fileName));fileIO.deleteFile(fileName);}}//輸出://success//你好!//hello//姓名:張三 年齡:3

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.