欢迎光临散文网 会员登陆 & 注册

java第三方ApacheIO包

2022-08-31 09:59 作者:虚云幻仙  | 我要投稿

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
import org.apache.commons.io.filefilter.IOFileFilter;

import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Scanner;

/**
* ApacheIO包
* www.apache.org提供的开源项目Commons中的IO包
*/

public class ApacheCommonsIO1 {
   public static void main(String[] args) {
       try {
           String s = FileUtils.readFileToString(new File("iostream/testFile.txt"),"utf-8");
           //FileUtils工具包,所有方法都为静态方法可用类直接调用,.readFileToString(File f,String charset)方法需要传入File对象和指定的字符集,将文件中的内容转换为字符串
           //java中字节流转字符流同样需要字符集,当没有指定字符集时默认使用utf-8
           //InputStreamReader isr = new InputStreamReader(new FileInputStream("fas"),"utf-8");使用转换流时如果只传InputStream对象一个参数会默认使用utf-8,两个参数时可对第二个参数设定字符集

           System.out.println(s);
           //将所有内容全部读出
       } catch (IOException e) {
           throw new RuntimeException(e);
       }

       try {
           FileUtils.copyDirectory(new File("c:/Aa"), new File("c:/Bb"), new FileFilter() {
               //.copyDirectory(File srcDir,File destDir,FileFilter filter)将源目录src内的内容全部拷贝到目标目录dest,如果目标目录不存在会创建该目录,FileFilter接口用于筛选文件filter过滤器,使用过滤器仅拷贝筛选的文件
               @Override
               public boolean accept(File pathname) {
                   //匿名内部类,需要实现FileFilter接口的方法accept(File pathname),pathname为src目录内的每一个文件,当一个文件符合筛选条件时返回true执行拷贝,返回false跳过该文件
                   String name = pathname.getName();
                   return name.endsWith(".doc") || name.endsWith(".ppt") || pathname.isDirectory();
                   //当文件是doc/ppt/目录时返回true,简写为return 判断结果
                   //如果不允许拷贝目录则不会对Aa目录的子目录内的内容进行拷贝

               }
           });
       } catch (IOException e) {
           throw new RuntimeException(e);
       }

       try {
           FileUtils.cleanDirectory(new File("c:/Bb"));
           //.cleanDirectory()清空目录内的内容
       } catch (IOException e) {
           throw new RuntimeException(e);
       }

       try {
           boolean b = FileUtils.contentEquals(new File("C:/Aa/a.txt"), new File("C:/Bb/b.txt"));
           //比较两个文件的内容是否相同
           System.out.println(b);
       } catch (IOException e) {
           throw new RuntimeException(e);
       }

       try {
           FileUtils.copyFile(new File("C:/Aa/001.jpg"),new File("c:/Bb/we/001.jpg"));
           //拷贝文件,如果目标路径中某级目录不存在会创建目录树
       } catch (IOException e) {
           throw new RuntimeException(e);
       }

       try {
           FileUtils.copyFileToDirectory(new File("C:/Aa/001.jpg"),new File("c:/Bb/wd"));
           //拷贝文件到目录,和copyFile的区别是只能指定目的地目录而不能改变文件名
       } catch (IOException e) {
           throw new RuntimeException(e);
       }

       Scanner sc = new Scanner(System.in);
       System.out.print("你有权保持沉默。如果你不保持沉默,那么你所说的一切都能够用作为你的呈堂证供。你有什么要说的吗:");
       String content = sc.nextLine();
       ByteArrayInputStream bais = new ByteArrayInputStream(content.getBytes());
       try {
           FileUtils.copyInputStreamToFile(bais,new File("c:/Bb/userInput.txt"));
           //拷贝输入流中的内容到文件,如果文件已存在会覆盖文件
           System.out.println("你的供述已被保存至c:/Bb/userInput.txt文件中");
       } catch (IOException e) {
           throw new RuntimeException(e);
       }

       try {
           FileUtils.deleteDirectory(new File("c:/Bb/we"));
           //删除目录,无论目录内是否有内容都会将目录整个删除
       } catch (IOException e) {
           throw new RuntimeException(e);
       }

       boolean b = FileUtils.deleteQuietly(new File("c:/Bb/userInput.txt"));
       //删除文件,返回是否成功
       System.out.println(b);

       Collection<File> files = FileUtils.listFiles(new File("c:/Aa"), new IOFileFilter() {
           //.listFiles(File dir,IOFileFilter fileFilter,IOFileFilter dirFilter)返回dir目录下文件File对象的集合,fileFilter筛选文件不能为null,dirFilter筛选目录为null时不搜索子目录
           @Override
           public boolean accept(File file) {
               return true;
           }

           @Override
           public boolean accept(File file, String s) {
               return true;
           }
       }, new IOFileFilter() {
           @Override
           public boolean accept(File file) {
               return true;
           }

           @Override
           public boolean accept(File file, String s) {
               return true;
           }
       });
       System.out.println(files);
       //结果为:[c:\Aa\a\dfsadfs.ppt, c:\Aa\a\dsadsf.bmp, c:\Aa\fasd.doc] File对象集合中不包含目录的对象

       FileInputStream fis=null;
       try {
           fis = FileUtils.openInputStream(new File("c:/Aa/fasd.doc"));
           //打开指定文件的输入流FileInputStream
       } catch (IOException e) {
           throw new RuntimeException(e);
       }finally {
           if (fis != null) {
               try {
                   fis.close();
               } catch (IOException e) {
                   throw new RuntimeException(e);
               }
           }
       }

       try {
           List<String> strings = FileUtils.readLines(new File("iostream/testFile.txt"), "utf-8");
           //.readLines(File,charset)将文件每一行内容作为一个字符串组成List<String>对象返回
           System.out.println(strings);
       } catch (IOException e) {
           throw new RuntimeException(e);
       }

       System.out.println(FileUtils.sizeOf(new File("c:/Aa"))/1024);
       //.sizeOf(File)返回文件的大小/字节数,long类型

       try {
           FileUtils.write(new File("iostream/testFile.txt"),"1111","utf-8");
           //.write(File,data,charset)将data字符序列直接写入文件中,会覆盖原文件
       } catch (IOException e) {
           throw new RuntimeException(e);
       }

       byte[] content2 = "将字节数据写入文件".getBytes();
       try {
           FileUtils.writeByteArrayToFile(new File("iostream/testFile.txt"),content2,true);
           //.writeByteArrayToFile(File,content,boolean append),append=true会在原文件后续写,false或不传第三个参数会覆盖
       } catch (IOException e) {
           throw new RuntimeException(e);
       }

       ArrayList<Integer> arr = new ArrayList<>();
       arr.add(1);
       arr.add(0);
       arr.add(6);
       try {
           FileUtils.writeLines(new File("iostream/testFile.txt"),arr,true);
           //.writeLines(File,Collection,boolean append)将Collection集合写入文件,每一个元素写入.toString()的字符串
       } catch (IOException e) {
           throw new RuntimeException(e);
       }

       try {
           FileUtils.writeStringToFile(new File("iostream/testFile.txt"),"直接将字符串写入文件","utf-8",true);
       } catch (IOException e) {
           throw new RuntimeException(e);
       }

       //IOUtils工具类
       BufferedInputStream bis=null;
       fis=null;
       BufferedOutputStream bos=null;
       try {
           bis = IOUtils.buffer(new FileInputStream("iostream/testFile.txt"));
           //.buffer(Stream)包装一层缓冲流返回,选填第二个参数size指定缓冲大小
           bos = IOUtils.buffer(new FileOutputStream("iostream/testFile2.txt"));
           int copy = IOUtils.copy(bis, bos);
           //.copy(InputStream/Reader,OutputStream/Writer),将输入流的内容拷贝到输出流,返回拷贝的字节数
           //.copyLarge()拷贝大于2G的内容时使用

           fis = new FileInputStream("iostream/testFile2.txt");
           boolean bb = IOUtils.contentEquals(bis, fis);
           //比较两个输入流中的内容是否一致
           System.out.println(bb);
       } catch (FileNotFoundException e) {
           throw new RuntimeException(e);
       } catch (IOException e) {
           throw new RuntimeException(e);
       } finally {
           IOUtils.closeQuietly(bis,fis,bos);
           //.closeQuietly(Stream)关闭流,可变参数
       }

       FileReader fr = null;
       FileWriter fw = null;
       try {
           fr = new FileReader("iostream/testFile2.txt");
           LineIterator iterator = IOUtils.lineIterator(fr);
           //.lineIterator(InputStream/Reader)返回一个输入流的逐行迭代器,每一行都不包含换行/r/n
           while (iterator.hasNext()){
               System.out.println(iterator.next());
           }
           char[] buff = new char[100];
           int num = IOUtils.read(fr, buff);
           //.read()将输入流中的内容读到数组中,字符流对char[],字节流对byte[],返回读入数组的字符/字节数
           System.out.println(num);
           //结果为32
           IOUtils.readFully(fr,buff);
           //.readFully()将输入流的内容填满数组,如果数组填不满会抛EOFException: Length to read: 100 actual: 32
           List<String> lines = IOUtils.readLines(fr);
           //.readLines()返回每一行字符串的集合
           BufferedReader br = IOUtils.toBufferedReader(fr);
           //.toBufferedReader/InputStream包装缓冲流
           byte[] bytes = IOUtils.toByteArray(fr, "utf-8");
           //.toByteArray()/.toCharArray()将输入流的内容转为字节数组或字符数组
           System.out.println(IOUtils.toString(fr));
           //.toString()将输入流或字节数组转化为字符串,非字符流需要指定字符集
           fw = new FileWriter("iostream/testFile2.txt");
           IOUtils.write("将内容写进输出流",fw);
           arr = new ArrayList<>();
           arr.add(1);
           arr.add(1);
           arr.add(1);
           IOUtils.writeLines(arr,"自定义每行的行尾,null默认为换行符,如果自定义不加换行符会全都写在一行",fw);
           //.writeLines(Collection<?>,String lineEnding,OutputStream/Writer)写入任意集合的每个元素的toString字符串


       } catch (FileNotFoundException e) {
           throw new RuntimeException(e);
       } catch (IOException e) {
           throw new RuntimeException(e);
       } finally {
           IOUtils.closeQuietly(fr,fw);
       }


   }
}

java第三方ApacheIO包的评论 (共 条)

分享到微博请遵守国家法律