java 常用IO操作

來源:互聯網
上載者:User

java中有關IO操作的API太多了,而且因為曆史原因,有些api已經被廢棄,有時不免讓一些初學者比較迷糊,今天抽時間整理了我平時常用的流操作,分享出來,如果有寫錯的地方,還請大家指正,因為大部分方法都寫了注釋,所以main中的測試代碼就不寫注釋了.

對於理論性的資料大家可參閱http://www.blogjava.net/spark/archive/2006/09/29/72733.html這位朋友總結的非常好,如果大家對理論已經有所認知,正需要動手操作的話下面的代碼正適合你.

2008.07.03進行了重新編輯,新增加了一些方法。

package com.syj.util;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.OutputStream;import java.io.PrintWriter;import java.io.Reader;import java.io.StringReader;import java.io.StringWriter;import java.io.Writer;import java.util.Arrays;/** * <p> * Title:IO工具類 * </p> *  * <p> * Description:常用的IO操作封裝 * </p> *  * <p> * Copyright: 轉載請註明出處http://blog.csdn.net/sunyujia/ * </p> *  * @author 孫鈺佳 * @main sunyujia@yahoo.cn * @date Jun 15, 2008 4:37:58 PM */public class IOUtil {/** * 緩衝區大小 1MB */private static final int BUFFER_SIZE = 1024 * 1024;/** *  * Description: 將輸入資料流輸出到輸出資料流 *  * @param in *            輸入資料流 * @param out *            輸出資料流 * @param bufferSize *            緩衝區大小 * @throws IOException * @mail sunyujia@yahoo.cn * @since:Jun 15, 2008 5:57:24 PM */public static void in2OutStream(InputStream in, OutputStream out,int bufferSize) throws IOException {byte[] buffer = new byte[bufferSize];// 緩衝區for (int bytesRead = 0; (bytesRead = in.read(buffer)) != -1;) {out.write(buffer, 0, bytesRead);Arrays.fill(buffer, (byte) 0);}}/** *  * Description:將read中的內容寫入writer *  * @param in * @param out * @param bufferSize * @throws IOException * @mail sunyujia@yahoo.cn * @since:Jul 2, 2008 11:22:42 PM */public static void read2Writer(Reader in, Writer out, int bufferSize)throws IOException {char[] buffer = new char[bufferSize];// 緩衝區for (int bytesRead = 0; (bytesRead = in.read(buffer)) != -1;) {out.write(buffer, 0, bytesRead);buffer = new char[bufferSize];}}/** *  * Description:將read中的內容寫入writer(逐行) *  * @param in * @param out * @param bufferSize * @throws IOException * @mail sunyujia@yahoo.cn * @since:Jul 2, 2008 11:22:42 PM */public static void read2Writer(BufferedReader in, PrintWriter out)throws IOException {for (String line; (line = in.readLine()) != null;) {out.println(line);}}/** *  * Description: 讀取檔案返回位元組數組流 *  * @param file *            檔案 * @return 位元組數組流 * @mail sunyujia@yahoo.cn * @since:Jun 15, 2008 4:52:41 PM */public static ByteArrayOutputStream readFileToByteStream(File file)throws IOException {FileInputStream fis = null;ByteArrayOutputStream bos = null;try {fis = new FileInputStream(file);bos = new ByteArrayOutputStream();in2OutStream(fis, bos, BUFFER_SIZE);} finally {if (fis != null)fis.close();}return bos;}/** *  * Description:讀取檔案返回位元組數組 *  * @param file *            檔案 * @return 位元組數組 * @throws IOException * @mail sunyujia@yahoo.cn * @since:Jun 15, 2008 5:38:50 PM */public static byte[] readFileToByteArray(File file) throws IOException {ByteArrayOutputStream bos = null;try {bos = readFileToByteStream(file);} finally {if (bos != null)bos.close();}return bos.toByteArray();}/** *  * Description:從Reader對象中讀取字串 *  * @param reader * @return * @throws IOException * @mail sunyujia@yahoo.cn * @since:Jul 2, 2008 11:08:32 PM */public static String readString(Reader reader) throws IOException {PrintWriter sw = null;BufferedReader in = null;try {in = new BufferedReader(reader);StringWriter swr = new StringWriter();sw = new PrintWriter(swr, true);read2Writer(in, sw);return swr.toString();} finally {try {if (in != null)in.close();} finally {if (sw != null)sw.close();}}}/** *  * Description:讀取檔案內容 *  * @param file *            檔案 * @return String內容 * @throws IOException * @mail sunyujia@yahoo.cn * @since:Jun 15, 2008 5:46:32 PM */public static String readFileToString(File file) throws IOException {return readString(new FileReader(file));}/** *  * Description:複製檔案 *  * @param src *            源檔案 * @param dest *            目標檔案 * @param cover *            是否覆蓋 * @throws IOException * @mail sunyujia@yahoo.cn * @since:Jun 15, 2008 6:08:28 PM */public static void copyFile(File src, File dest, boolean cover)throws IOException {FileInputStream in = null;FileOutputStream out = null;try {if (!dest.exists()) {dest.createNewFile();} else if (dest.exists() && cover) {dest.delete();dest.createNewFile();} else {return;}in = new FileInputStream(src);out = new FileOutputStream(dest);in2OutStream(in, out, BUFFER_SIZE);} finally {try {if (in != null)in.close();} finally {if (out != null)out.close();}}}/** *  * Description:寫檔案 *  * @param file *            檔案 * @param str *            內容 * @throws IOException * @mail sunyujia@yahoo.cn * @since:Jun 15, 2008 6:17:24 PM */public static void writeFile(File file, String str) throws IOException {PrintWriter out = null;BufferedReader in = null;try {if (!file.exists())file.createNewFile();in = new BufferedReader(new StringReader(str));out = new PrintWriter(new BufferedWriter(new FileWriter(file)));read2Writer(in, out);} finally {try {if (in != null)in.close();} finally {if (out != null)out.close();}}}/** *  * Description:從控制台讀取一串字串 *  * @return 讀取的字串 * @throws IOException * @mail sunyujia@yahoo.cn * @since:Jun 15, 2008 6:42:29 PM */public static String readStringFromSystemIn() throws IOException {BufferedReader br = new BufferedReader(new InputStreamReader(System.in));try {return br.readLine();} finally {if (br != null)br.close();}}/** *  * Description:當ObjectInputStream對象調用 * readObject();時,會從ByteArrayInputStream流中還原序列化出的對象 *  *  * @param bi * @return * @throws IOException * @mail sunyujia@yahoo.cn * @since:Jun 15, 2008 7:07:53 PM */public static ObjectInputStream buildObjectInputStream(ByteArrayInputStream bi) throws IOException {return new ObjectInputStream(bi);}/** *  * Description:當ObjectOutputStream對象調用 * writeObject(o);時,o對象會序列化到ByteArrayOutputStream流中去 *  * @param bos *            位元組數組流 * @return 對象輸出資料流 * @throws IOException * @mail sunyujia@yahoo.cn * @since:Jun 15, 2008 7:06:00 PM */public static ObjectOutputStream buildObjectOutputStream(ByteArrayOutputStream bos) throws IOException {return new ObjectOutputStream(bos);}public static BufferedReader buildBufferedReader(String str) {return new BufferedReader(new StringReader(str));}public static ByteArrayInputStream buildByteArrayInputStream(String str) {return new ByteArrayInputStream(str.getBytes());}public static ByteArrayInputStream buildByteArrayInputStream(byte[] bt) {return new ByteArrayInputStream(bt);}public static BufferedReader buildReader(InputStream is) {return new BufferedReader(new InputStreamReader(is));}/** *  * Description:測試代碼 *  * @param args * @throws Exception * @mail sunyujia@yahoo.cn * @since:Jul 3, 2008 8:18:33 PM */public static void main(String[] args) throws Exception {byte[] bootFileBytes = IOUtil.readFileToByteArray(new File("C://boot.ini"));System.out.println(new String(bootFileBytes));String bootFileStr = readFileToString(new File("C://boot.ini"));System.out.println(bootFileStr);System.out.println(new String(bootFileBytes).equals(bootFileStr));IOUtil.copyFile(new File("C://boot.ini"), new File("C://boot1.ini"),true);IOUtil.writeFile(new File("C://boot2.ini"), bootFileStr);ByteArrayOutputStream bos = new ByteArrayOutputStream();ObjectOutputStream oos = IOUtil.buildObjectOutputStream(bos);oos.writeObject(new String("abcd"));ObjectInputStream ois = IOUtil.buildObjectInputStream(IOUtil.buildByteArrayInputStream(bos.toByteArray()));System.out.println(ois.readObject());System.out.println(IOUtil.readString(new StringReader("測試")));System.out.println(IOUtil.readStringFromSystemIn());}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.