1. 程式人生 > >Java程序員的日常—— IOUtils總結

Java程序員的日常—— IOUtils總結

clas nco als 默認 ktr verilog arraylist tps 什麽

以前寫文件的復制很麻煩,需要各種輸入流,然後讀取line,輸出到輸出流...其實apache.commons.io裏面提供了輸入流輸出流的常用工具方法,非常方便。下面就結合源碼,看看IOUTils都有什麽用處吧!
代碼參考https://github.com/xinghalo/JDK-Learning

常用的靜態變量

在IOUtils中還是有很多常用的一些變量的,比如換行符等等


public static final char DIR_SEPARATOR_UNIX = ‘/‘;
public static final char DIR_SEPARATOR_WINDOWS = ‘\\‘;
public
static final char DIR_SEPARATOR; public static final String LINE_SEPARATOR_UNIX = "\n"; public static final String LINE_SEPARATOR_WINDOWS = "\r\n"; public static final String LINE_SEPARATOR; static { DIR_SEPARATOR = File.separatorChar; StringBuilderWriter buf = new StringBuilderWriter(4
); PrintWriter out = new PrintWriter(buf); out.println(); LINE_SEPARATOR = buf.toString(); out.close(); }

常用方法

copy

這個方法可以拷貝流,算是這個工具類中使用最多的方法了。支持多種數據間的拷貝:

copy(inputstream,outputstream)
copy(inputstream,writer)
copy(inputstream,writer,encoding)
copy(reader,outputstream)
copy(reader,writer)
copy(reader,writer,encoding)

copy內部使用的其實還是copyLarge方法。因為copy能拷貝Integer.MAX_VALUE的字節數據,即2^31-1。

copyLarge

這個方法適合拷貝較大的數據流,比如2G以上。

copyLarge(reader,writer) 默認會用1024*4buffer來讀取
copyLarge(reader,writer,buffer)

內部的細節可以參考:

 public static long copyLarge(Reader input, Writer output, char [] buffer) throws IOException {
        long count = 0;
        int n = 0;
        while (EOF != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
            count += n;
        }
        return count;
    }

這個方法會用一個固定大小的Buffer,持續不斷的讀取數據,然後寫入到輸出流中。

read

從一個流中讀取內容

read(inputstream,byte[])
read(inputstream,byte[],offset,length) 
//offset是buffer的偏移值,length是讀取的長度

read(reader,char[])
read(reader,char[],offset,length)

這裏我寫了個小例子,可以測試read方法的效果:

@Test
    public void readTest(){
        try{
            byte[] bytes = new byte[4];
            InputStream is = IOUtils.toInputStream("hello world");
            IOUtils.read(is, bytes);
            System.out.println(new String(bytes));

            bytes = new byte[10];
            is = IOUtils.toInputStream("hello world");
            IOUtils.read(is, bytes, 2, 4);
            System.out.println(new String(bytes));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

得到的結果是:

hell
□□hell□□□□

readFully

這個方法會讀取指定長度的流,如果讀取的長度不夠,就會拋出異常

readFully(inputstream,byte[])
readFully(inputstream,byte[],offset,length)
readFully(reader,charp[])
readFully(reader,char[],offset,length)

比如:

@Test
    public void readFullyTest(){
        byte[] bytes = new byte[4];
        InputStream is  = IOUtils.toInputStream("hello world");
        try {
            IOUtils.readFully(is,bytes);
            System.out.println(new String(bytes));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

輸出

hell

但是如果讀取20個byte,就會出錯了

java.io.EOFException: Length to read: 20 actual: 11
    at org.apache.commons.io.IOUtils.readFully(IOUtils.java:2539)
    at org.apache.commons.io.IOUtils.readFully(IOUtils.java:2558)
    at test.java.IOUtilsTest.readFullyTest(IOUtilsTest.java:22)
    ...

readLines

readLines方法可以從流中讀取內容,並轉換為String的list

readLines(inputstream)
readLines(inputstream,charset)
readLines(inputstream,encoding)
readLines(reader)

這個方法極大簡化了之前原始的讀取方法:

 @Test
    public void readLinesTest(){
        try{
            InputStream is = new FileInputStream("D://test1.txt");
            List<String> lines = IOUtils.readLines(is);
            for(String line : lines){
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

輸出內容:

hello
world

nihao
ioutils

skip

這個方法用於跳過指定長度的流,

skip(inputstream,skip_length)
skip(ReadableByteChannel,skip_length)
skip(reader,skip_length)

例如:

@Test
    public void skipTest(){
        InputStream is = IOUtils.toInputStream("hello world");
        try {
            IOUtils.skip(is,4);
            System.out.println(IOUtils.toString(is,"utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

skipFully

這個方法類似skip,只是如果忽略的長度大於現有的長度,就會拋出異常

skipFully(inputstream,toSkip)
skipFully(readableByteChannel,toSkip)
skipFully(inputstream,toSkip)

例如

@Test
    public void skipFullyTest(){
        InputStream is = IOUtils.toInputStream("hello world");
        try {
            IOUtils.skipFully(is,30);
            System.out.println(IOUtils.toString(is,"utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

write

這個方法可以把數據寫入到輸出流中

write(byte[] data, OutputStream output)
write(byte[] data, Writer output)
write(byte[] data, Writer output, Charset encoding)
write(byte[] data, Writer output, String encoding)
write(char[] data, OutputStream output)
write(char[] data, OutputStream output, Charset encoding)
write(char[] data, OutputStream output, String encoding)
write(char[] data, Writer output)
write(CharSequence data, OutputStream output)
write(CharSequence data, OutputStream output, Charset encoding)
write(CharSequence data, OutputStream output, String encoding)
write(CharSequence data, Writer output)
write(StringBuffer data, OutputStream output)
write(StringBuffer data, OutputStream output, String encoding)
write(StringBuffer data, Writer output)
write(String data, OutputStream output)
write(String data, OutputStream output, Charset encoding)
write(String data, OutputStream output, String encoding)
write(String data, Writer output)

例如

@Test
    public void writeTest(){
        try {
            OutputStream os = new FileOutputStream("E:/test.txt");
            IOUtils.write("hello write!",os);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

writeLines

這個方法可以把string的List寫入到輸出流中

writeLines(Collection<?> lines, String lineEnding, OutputStream output)
writeLines(Collection<?> lines, String lineEnding, OutputStream output, Charset encoding)
writeLines(Collection<?> lines, String lineEnding, OutputStream output, String encoding)
writeLines(Collection<?> lines, String lineEnding, Writer writer)

例如

@Test
    public void writeLinesTest() throws IOException {
        List<String> lines = new ArrayList();
        lines.add("hello");
        lines.add("list");
        lines.add("to");
        lines.add("file");
        OutputStream os = new FileOutputStream("E:/test.txt");
        IOUtils.writeLines(lines,IOUtils.LINE_SEPARATOR,os);
    }

close

關閉URL連接

close(URLConnection conn)

closeQuietly

忽略nulls和異常,關閉某個流

close(URLConnection conn)
closeQuietly(Closeable... closeables)
closeQuietly(Closeable closeable)
closeQuietly(InputStream input)
closeQuietly(OutputStream output)
closeQuietly(Reader input)
closeQuietly(Selector selector)
closeQuietly(ServerSocket sock)
closeQuietly(Socket sock)
closeQuietly(Writer output)

contentEquals

比較兩個流是否相同

contentEquals(InputStream input1, InputStream input2)
contentEquals(Reader input1, Reader input2)

例如

@Test
    public void contentEqualsTest(){
        InputStream is1 = IOUtils.toInputStream("hello123");
        InputStream is2 = IOUtils.toInputStream("hello123");

        try {
            System.out.println(IOUtils.contentEquals(is1,is2));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

contentEqualsIgnoreEOL

比較兩個流,忽略換行符

contentEqualsIgnoreEOL(Reader input1, Reader input2)

lineIterator

讀取流,返回叠代器

lineIterator(InputStream input, Charset encoding)
lineIterator(InputStream input, String encoding)
lineIterator(Reader reader)

toBufferedInputStream

把流的全部內容放在另一個流中

toBufferedInputStream(InputStream input)
toBufferedInputStream(InputStream input, int size)

toBufferedReader

返回輸入流

toBufferedReader(Reader reader)
toBufferedReader(Reader reader, int size)

toByteArray

返回字節數組

toByteArray(InputStream input)
toByteArray(InputStream input, int size)
toByteArray(InputStream input, long size)
toByteArray(Reader input)
toByteArray(Reader input, Charset encoding)
toByteArray(Reader input, String encoding)
toByteArray(String input)
toByteArray(URI uri)
toByteArray(URL url)
toByteArray(URLConnection urlConn)

toCharArray

返回字符數組

toCharArray(InputStream is)
toCharArray(InputStream is, Charset encoding)
toCharArray(InputStream is, String encoding)
toCharArray(Reader input)

toInputStream

返回輸入流

toInputStream(CharSequence input)
toInputStream(CharSequence input, Charset encoding)
toInputStream(CharSequence input, String encoding)
toInputStream(String input)
toInputStream(String input, Charset encoding)
toInputStream(String input, String encoding)

toString

返回字符串

toString(byte[] input)
toString(byte[] input, String encoding)
toString(InputStream input)
toString(InputStream input, Charset encoding)
toString(InputStream input, String encoding)
toString(Reader input)
toString(URI uri)
toString(URI uri, Charset encoding)
toString(URI uri, String encoding)
toString(URL url)
toString(URL url, Charset encoding)
toString(URL url, String encoding)

Java程序員的日常—— IOUtils總結