IOUtils总结

常用的静态变量

在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*4的buffer来读取
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)

原文地址:https://www.cnblogs.com/xwb583312435/p/9015772.html

时间: 2024-10-02 21:05:53

IOUtils总结的相关文章

利用commons-io.jar包中FileUtils和IOUtils工具类操作流及文件

1.String IOUtils.toString(InputStream input),传入输入流对象,返回字符串,有多重重载,可按需要传参 用例: @Test public void showInfoByIOUtils() throws IOException { URL url = new URL("https://www.baidu.com"); InputStream in = url.openStream(); System.out.println(in); try { S

Tomcat中使用commons-io-2.5发生的错误java.lang.ClassNotFoundException: org.apache.commons.io.IOUtils

关键词:IntelliJ IDEA.Tomcat.commons-io-2.5.jar.java.lang.ClassNotFoundException: org.apache.commons.io.IOUtils 1.错误提示信息 图1 运行登录时错误信息 //Tomcat Localhost Log信息 org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [Servlet] in

10.10-全栈Java笔记:Apache IOUtils和FileUtils的使用

JDK中提供的文件操作相关的类,功能非常基础,进行复杂操作时需要做大量编程工作.实际开发中,往往需要你自己动手编写相关的,尤其在遍历目录文件时,经常用到递归,非常繁琐. Apache-commons工具包中提供了FileUtils,可以让我们非常方便的对文件和目录进行操作. 本文就是让大家对FileUtils类有一个全面的认识,便于大家以后开发文件和目录相关功能. Apache IOUtils和FileUtils类库为我们提供了更加简单.功能更加强大的文件操作和IO流操作功能.非常值得大家学习和

IOUtils

package com.itheima.googleplay_8.utils; import java.io.Closeable; import java.io.IOException; public class IOUtils { /** 关闭流 */ public static boolean close(Closeable io) { if (io != null) { try { io.close(); } catch (IOException e) { LogUtils.e(e); }

使用Apache的IOUtils实现文件下载

废话不多说,直接上代码,注释写得也比较清楚. /** * 下载模板文件 * @param filename 要下载的文件在工程中的路径,如/template/userTemplate.xls */ @RequestMapping("/common/downloadtemplatefile") public void downloadTemplateFile(String filename, HttpServletResponse response, HttpServletRequest

Delphi FMX 手机目录提取,把IO相关的都提取到System.IoUtils单元中

Delphi把IO相关的都提取到System.IoUtils单元中.路径操作使用TPath的方法都很方便.uses System.IoUtils TPath.GetTempPath//临时目录TPath.GetCameraPath//照相机目录(照片/录像)TPath.GetMusicPath//音乐目录TPath.GetDownloadsPath//下载目录……如果使用TPath类的静态方法那么代码就是跨平台的,在Windows,Mac,iOS,Android上都能用.如果仅仅对Android

java 实现下载htttp文件的简便办法 FileUtils IOUtils

其实很多时候,我们并不需要去重复造轮子,只需要借 就可以.但是前提就得你得知道谁家有轮子可借才行.这次就用到了 org.apache.common.io 家的轮子了. 具体实现: public String downloadHttpUrl(String url, String dir) { String fileName = "test.jpg"; try { URL httpurl = new URL(url); File f = new File(dir + fileName);

Commons-IO - IOUtils

IOUtils is a general IO stream manipulation utilities. This class provides static utility methods for input/output operations. closeQuietly - these methods close a stream ignoring nulls and exceptions toXxx/read - these methods read data from a strea

IOUtils方式上传下载文件

package com.css.hdfs04; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import org.apache.hadoop.conf.Configuration; import org