从JavaIO到CommonsIO

从JavaIO到CommonsIO

JavaIO

数据源:File类

基础操作:

package com.file;

import java.io.File;
import java.io.IOException;

import org.junit.Test;

public class TestFile {
	private String path = "src/test/resources";
	@Test
	/**
	 * 直接写new File("文件路径")这样构造也是可以的;
	 * 还可以new File(父File,"文件名");
	 * 下面用的是new File("父路径","文件名");
	 */
	public void testFileMethods() {
		File file = new File(path,"maven.png");
		System.out.println("文件是否存在:"+file.exists());
		System.out.println("是否为文件:"+file.isFile());
		System.out.println("是否为文件夹:"+file.isDirectory());
		System.out.println("文件路径(可相对可绝对):"+file.getPath());
		System.out.println("文件绝对路径:"+file.getAbsolutePath());
		System.out.println("文件父路径:"+file.getParent());
		System.out.println("父级文件:"+file.getParentFile());
		System.out.println("文件大小(字节):"+file.length());
		System.out.println("文件名:"+file.getName());
	}
	
	@Test
	/**
	 * 只能创建文件,不能创建文件夹;
	 * 有同名文件直接创建失败,返回false;
	 * @throws IOException
	 */
	public void testCreateFile() throws IOException {
		File file = new File(path,"test.txt");
		boolean flag = file.createNewFile();
		System.out.println(flag);
	}
	
	@Test
	public void testDeleteFile() {
		File file = new File(path,"test.txt");
		boolean flag = file.delete();
		System.out.println(flag);
	}
	
	@Test
	/**
	 * mkdir()父级目录必须存在;
	 * mkdirs父级目录可以不存在,一同创建;
	 * 推荐使用mkdirs();
	 */
	public void testMkdirs() {
		File dir1 = new File(path,"test");
		boolean flag = dir1.mkdir();
		System.out.println(flag);
		File dir2 = new File(path,"test2/test3");
		flag = dir2.mkdirs();
		System.out.println(flag);
	}
	
	@Test
	/**
	 * list()列出下一级文件(夹)的名称;
	 * listFiles列出下一级文件(夹)的File对象;
	 */
	public void testList() {
		File file = new File(path);
		for(String fileName:file.list()) {
			System.out.println(fileName);
		}
		System.out.println("-----------------");
		for(File f:file.listFiles()) {
			System.out.println(f);
		}
	}
	
}

节点流

字节流

共有FileInputStream、FileOutputStream、ByteArrayInputStream、ByteArrayOutputStream四个,两对;

package com.bytestream;

import java.io.ByteArrayInputStream;
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 org.junit.Test;

public class TestByteStream {
	private String path = "src/test/resources";
	
	@Test
	/**文件字节输入流
	 * 数据源:文件;
	 * is.read()返回值是读到的那一个字节,文件末尾返回-1;
	 * is.read(byte[])是一次性读很多个字节,返回值是读到的长度,读到的字节存在byte[]中,文件末尾返回-1;
	 * 一般都是使用is.read(byte[])这种;
	 */
	public void testFileInputStream() {
		File file = new File(path,"test.txt");
		InputStream is = null;
		try {
			is = new FileInputStream(file);
			byte[] flush = new byte[1024];
			int len;
			while((len=is.read(flush))!=-1) {
				String str = new String(flush,0,len);
				System.out.println(str);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	@Test
	/**文件字节输出流
	 * 目的地:文件;
	 * os.write(byte[],0,byte.length)是向流中写入字节数组,0代表从byte的第0个位置开始,第三个参数代表写入长度;
	 * FileOutputStream的构造方法的第二个参数代表是否追加;
	 * 若FileOutputStream构造时只有一个参数或者第二个参数为false代表重写文件;
	 */
	public void testFileOutputStream() {
		File file = new File(path,"test2.txt");
		OutputStream os = null;
		try {
			os = new FileOutputStream(file,true);
			String str = "Hello World!";
			byte[] data = str.getBytes();
			os.write(data,0,data.length);
			os.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(os != null) {
					os.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Test
	/**字节数组输入流
	 * 数据源是一个字节数组byte[];
	 * 不需要关闭,因为是从内存中取的数据,由JVM自己垃圾回收;
	 */
	public void testByteArrayInputStream() {
		byte[] data = "ByteArrayInputStream".getBytes();
		InputStream is = null;
		try {
			is = new ByteArrayInputStream(data);
			byte[] flush = new byte[1024];
			int len;
			while((len=is.read(flush))!=-1) {
				String str = new String(flush,0,len);
				System.out.println(str);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Test
	/**字节数组输出流
	 * 不需要指定目的地,write方法会写入到流中;
	 * 若想取出流中数据,可使用toByteArray()方法;
	 */
	public void testByteArrayOutputStream() {
		ByteArrayOutputStream os = null;
		try {
			os = new ByteArrayOutputStream();
			byte[] str = "Hello World!".getBytes();
			os.write(str,0,str.length);
			os.flush();
			System.out.println(new String(os.toByteArray()));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

字符流

有FileReader、FileWriter;

package com.charstream;

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;

import org.junit.Test;

public class TestCharStream {
	private String path = "src/test/resources";
	
	@Test
	/**文件字符输入流
	 * 使用方法同InputStream,但是对于文本的处理更好;
	 * 读入的是字符数组,不再是字节数组;
	 * 一般都是使用Reader或writer来处理文本,而非InputStream和OutputStream;
	 */
	public void testFileReader() {
		File file = new File(path,"test.txt");
		Reader reader = null;
		try {
			reader = new FileReader(file);
			char[] flush = new char[1024];
			int len;
			while((len=reader.read(flush))!=-1) {
				String str = new String(flush,0,len);
				System.out.println(str);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(reader != null) {
					reader.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	@Test
	/**文件字符输出流
	 * 可以写入字符数组,也可以直接写入字符串;
	 * 构造方同FileOutputStream;
	 */
	public void testFileWriter() {
		File file = new File(path,"test2.txt");
		Writer writer = null;
		try {
			writer = new FileWriter(file,true);
			writer.write("Hello World!");
			writer.append("你好世界!").append("你好世界!");
			writer.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(writer != null) {
					writer.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

处理流

处理流必须依赖于节点流,他会用装饰模式对节点流进行相应处理,对节点流增加一些功能

常见的处理流有以下这些:BufferedInputStream、BufferedOutputStream、BufferedReader、BufferWriter、InputStreamReader、OutputStreamWriter、DataInputStream、DataOutputStream、ObjectInputStream、ObjectOutputStream、PrintStream、PrintWriter;

package com.processstream;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
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.OutputStreamWriter;
import java.io.PrintStream;
import java.util.Date;

import org.junit.Test;

public class TestProcessStream {
	private String path = "src/test/resources";
	@Test
	/**字节缓冲输入流
	 * 作用:可提升性能;
	 */
	public void testBufferedInputStream() {
		File file = new File(path,"test.txt");
		InputStream is = null;
		try {
			is = new BufferedInputStream(new FileInputStream(file));
			byte[] flush = new byte[1024];
			int len;
			while((len=is.read(flush))!=-1) {
				String str = new String(flush,0,len);
				System.out.println(str);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	@Test
	/**字节缓冲输出流
	 * 作用:可提升性能;
	 */
	public void testBufferedOutputStream() {
		File file = new File(path,"test2.txt");
		OutputStream os = null;
		try {
			os = new BufferedOutputStream(new FileOutputStream(file,true));
			String str = "Hello World!";
			byte[] data = str.getBytes();
			os.write(data,0,data.length);
			os.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(os != null) {
					os.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Test
	/**字符字符输入流
	 * 作用:1.提升性能;
	 * 	   2.提供了readLine()方法,直接读一行文字,读不到返回null;
	 */
	public void testBufferedReader() {
		File file = new File(path,"test.txt");
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(file));
			String line = null;
			while((line=reader.readLine())!=null) {
				System.out.println(line);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(reader != null) {
					reader.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	@Test
	/**字符缓冲输出流
	 * 作用:1.提升性能;
	 *     2.提供了newLine(),添加换行符,不用手动敲\n;
	 */
	public void testFileOutputStream() {
		File file = new File(path,"test2.txt");
		BufferedWriter writer = null;
		try {
			writer = new BufferedWriter(new FileWriter(file,true));
			writer.write("Hello World!");
			writer.newLine();
			writer.append("你好世界!").append("你好世界!");
			writer.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(writer != null) {
					writer.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Test
	/**字节字符转换流:InputStreamReader,OutputStreamWriter
	 * 作用:将字节流转换为字符流,构造时第二个参数可以写解码方式;
	 * 
	 */
	public void testConvert() {
		BufferedReader reader = null;
		BufferedWriter writer = null;
		try {
			reader = new BufferedReader(new InputStreamReader(System.in));
			writer = new BufferedWriter(new OutputStreamWriter(System.out));
			String line = "";
			while(!line.equals("exit")) {
				line = reader.readLine();
				writer.write(line);
				writer.newLine();
				writer.flush();
			}
		}catch(IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(null != writer) {
					writer.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if(null != reader) {
					reader.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Test
	/**
	 * 数据字节流:DataInputStream,DataOutputStream
	 * 作用:可对基本数据类型和字符串进行读写,注意读写顺序必须保持一致
	 */
	public void testDataStream() {
		ByteArrayOutputStream baos = null;
		ObjectOutputStream dos = null;
		DataInputStream dis = null;
		ByteArrayInputStream bais = null;
		try {
			baos = new ByteArrayOutputStream();
			dos = new ObjectOutputStream(baos);
			dos.writeUTF("hello");
			dos.writeInt(2);
			dos.writeChar('g');
			dos.flush();
			byte[] data = baos.toByteArray();
			bais = new ByteArrayInputStream(data);
			dis = new DataInputStream(bais);
			System.out.println(dis.readUTF());
			System.out.println(dis.readInt());
			System.out.println(dis.readChar());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(null != dis) {
					dis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if(null != dos) {
					dos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	@Test
	/**
	 * 对象字节流:ObjectInputStream,ObjectOutputStream
	 * 作用:可对所有数据类型进行读写,注意读写顺序必须保持一致,注意对象必须实现Serializable接口
	 */
	public void testObjectStream() {
		ByteArrayOutputStream baos = null;
		ObjectOutputStream oos = null;
		ObjectInputStream ois = null;
		ByteArrayInputStream bais = null;
		try {
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(new Date());;
			oos.flush();
			byte[] data = baos.toByteArray();
			bais = new ByteArrayInputStream(data);
			ois = new ObjectInputStream(bais);
			System.out.println(ois.readObject());
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				if(null != ois) {
					ois.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if(null != oos) {
					oos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Test
	/**
	 * 打印流:PrintStream和PrintWriter
	 * 作用:直接打印到一个流中;
	 */
	public void testPrintStream() {
		PrintStream ps = null;
		try {
			ps = new PrintStream(new FileOutputStream(new File(path,"print.txt")));
			ps.println("hello");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			ps.close();
		}
	}
}

CommonsIO

CommonsIO也是根据以上基础封装而来的,使用起来很方便。

maven依赖:

<!-- commonsIO -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

具体使用:

package com.commons;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.EmptyFileFilter;
import org.junit.Test;

public class TestCommonsIO {
	private String path = "src/test/resources";
	
	@Test
	/**
	 * CommonsIO基本操作
	 */
	public void testBase() {
		System.out.println("文件大小为:"+FileUtils.sizeOf(new File(path,"maven.png")));
		System.out.println("文件夹大小为:"+FileUtils.sizeOf(new File(path)));
		//第二个参数是对文件的一些过滤,第三个参数是对文件夹的一些过滤
		Collection<File> files = FileUtils.listFiles(new File(path), EmptyFileFilter.NOT_EMPTY, DirectoryFileFilter.INSTANCE);
		for(File file:files) {
			System.out.println(file);
		}
	}
	
	@Test
	/**
	 * 读取很方便吧
	 */
	public void testRead() throws IOException {
		File file = new File(path,"test.txt");
		String msg = FileUtils.readFileToString(file,"gbk");
		byte[] data = FileUtils.readFileToByteArray(file);
		List<String> msgs = FileUtils.readLines(file,"gbk");
		LineIterator it = FileUtils.lineIterator(file);
		
		System.out.println(msg);
		
		System.out.println(data.length);
		
		for(String s:msgs) {
			System.out.println(s);
		}
		
		while(it.hasNext()) {
			System.out.println(it.nextLine());
		}
	}
	
	@Test
	/**
	 * 写入很方便吧
	 */
	public void testWrite() throws IOException {
		File file = new File(path,"CommonsIO.txt");
		//true表示追加
		FileUtils.write(file, "hello world\n","gbk",true);
		FileUtils.writeStringToFile(file, "string\n","gbk",true);
		FileUtils.writeByteArrayToFile(file, "byte\n".getBytes("gbk"),true);
		List<String> data = new ArrayList<String>();
		data.add("李");
		data.add("晶");
		data.add("晶");
		//第三个参数表示分隔符,默认是\n
		FileUtils.writeLines(file, data,"-",true);
	}
	
	@Test
	/**
	 * 拷贝
	 */
	public void testCopy() throws IOException {
		FileUtils.copyFile(new File(path,"test.txt"), new File(path,"test-copy.txt"));
		//还有一堆方法
//		FileUtils.copyDirectory(srcDir, destDir);
//		FileUtils.copyFileToDirectory(srcFile, destDir);
//		FileUtils.copyDirectoryToDirectory(srcDir, destDir);
		String url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1599757684887&di=6243d87f157c9b2f6293d079b00adee8&imgtype=0&src=http%3A%2F%2Ft8.baidu.com%2Fit%2Fu%3D3571592872%2C3353494284%26fm%3D79%26app%3D86%26f%3DJPEG%3Fw%3D1200%26h%3D1290";
		FileUtils.copyURLToFile(new URL(url), new File(path,"test.jpg"));
		String html = IOUtils.toString(new URL("https://www.163.com"),"gbk");
		System.out.println(html);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值