文件操作——读取、写入

package test.org.file;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FileOperation {

	public static final String[] fileBandString = { "图片文件", "jpeg2000", "tiff","psd", "png", "swf", "svg", "jpg", "jpeg", "pcx", "dxf", "wmf","emf", "gif", "bmp", 
																		"压缩文件", "rar", "zip", "7z", "cab", "iso",
																		"音频文件", "mp3", "wave", "aiff", "au", "mpeg", "cd", "mpeg-4","midi", "wma", "realaudio", "vof", "oggvorbis", 
																		"视频文件", "mp4","avi", "mov", "asf", "wmv", "navi", "3gp", "real video", "mkv","flv", "f4v", "rmvb", "webm" };

	public static final List<String> fileBandList = new ArrayList<String>(Arrays.asList(fileBandString));

	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		String filePath = "E:\\KuGou\\supplierss_save.jsp";
		filePath = "E:\\KuGou\\lvtu.mp3"; 

		getFilePath(filePath);
	}

	/**
	 * 以行为单位读取文件,常用于读面向行的格式化文件
	 * 
	 * @param filePath
	 * @throws Exception
	 */
	public static void readLineByFileOprea(String filePath) throws Exception {
		File file = new File(filePath);
		//字符 缓冲流
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
		//创建集合,存放读取的数据
		List<String> list = new ArrayList<String>();
		
		String line = null;
		//循环读取文件 直至读取的文件为空
		while ((line = br.readLine()) != null) {
			list.add(line);
		}
		//关闭流
		br.close();
		//调用写操作
		writeLineByFileOpera(filePath, list);
	}

	/**
	 * 以行为单位写入文件,常用于读面向行的格式化文件
	 * @param filePath
	 * @throws Exception
	 */
	public static void writeLineByFileOpera(String filePath, List list)throws Exception {
		String strName = getFileName(filePath);
		File file = new File(strName);

		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));

		for (Object obj : list) {
			bw.append((String) obj);
			bw.newLine(); // 创建新 的一行
		}
		System.out.println(strName + "  Line   创建完成");
		bw.close();
	}

	/**
	 * 读取文件单个字符 reader inutputSreamReader 字符流 以字符为单位读取文件,常用于读文本,数字等类型的文件
	 * 
	 * @param filePath
	 * @throws Exception
	 */
	public static void readCharByFileOprea(String filePath) throws Exception {
		File file = new File(filePath);

		InputStreamReader isr = new InputStreamReader(
				new FileInputStream(file), "UTF-8");

		List<Integer> list = new ArrayList<Integer>();

		int len = -1;
		while ((len = isr.read()) != -1) {
			list.add(len);
		}
		isr.close();
		writeCharByFileOpera(filePath, list);
	}

	/**
	 * 写入文件单个字符 writer outtputSreamWriter 字符流 以字符为单位写入文件,常用于读文本,数字等类型的文件
	 * @param filePath
	 * @throws Exception
	 */
	public static void writeCharByFileOpera(String filePath, List list)throws Exception {
		String strName = getFileName(filePath);
		File file = new File(strName);

		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream( file ), "UTF-8");

		for (Object obj : list) {
			osw.write((Integer) obj);
		}
		System.out.println(strName + "  Char   创建完成");
		osw.close();
	}

	/**
	 * 读取文件多个字符 reader inutputSreamReader 字符流 以字符为单位读取文件,常用于读文本,数字等类型的文件
	 * @param filePath
	 * @throws Exception
	 */
	public static void readCharsByFileOprea(String filePath) throws Exception {
		File file = new File(filePath);

		Reader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");

		List<Integer> list = new ArrayList<Integer>();

		char[] ch = new char[1024];
		int len = -1;
		while ((len = isr.read(ch)) != -1) {
			list.add(len);
		}
		isr.close();
		writeCharsByFileOpera(filePath, list, ch);
	}

	/**
	 * 写入文件单个字符 writer outtputSreamWriter 字符流
	 * @param filePath
	 * @throws Exception
	 */
	public static void writeCharsByFileOpera(String filePath, List list,char[] ch) throws Exception {
		String strName = getFileName(filePath);
		File file = new File(strName);

		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");

		for (Object obj : list) {
			osw.write((Integer) obj);
			osw.write(ch, 0, (Integer) obj);
		}
		System.out.println(strName + "   chars  创建完成");
		osw.close();
	}

	/**
	 * 读取文件单个字节 inputstream fileInputSream 字节流 常用于读二进制文件,如图片、声音、影像等文件
	 * @param filePath
	 * @throws IOException
	 */
	public static void readByteByFileOpera(String filePath) throws IOException {
	    	
		File file = new File(filePath);
		InputStream fis = null;
		fis = new FileInputStream(file);
		List<Integer> list = new ArrayList<Integer>();

		int len = -1;
		long time = System.currentTimeMillis();
		while ((len = fis.read()) != -1) {
			// 将读取的文件加入到集合中
			list.add(len);
//			//计算读取的长度
//			String st = getReadFilePlan(list.size() ,  file.length());
//			//打印进度
//			System.out.println(st);
		}
		fis.close();
		// 读取文件单个字节
		FileOperation.writeByteByfileOpera(filePath, list, time , file.length());
	}

	/**
	 * 写入文件单个字节 outputStream fileOutputSteram 字节流 常用于写二进制文件,如图片、声音、影像等文件
	 * @param filePath		文件路径
	 * @param list			存放数据的集合
	 * @param time		事件戳
	 * @param fileLength	源文件大小
	 * @throws IOException
	 */
	public static void writeByteByfileOpera(String filePath , List list , long time , long fileLength) throws IOException {
	    	//获取文件名字
	    	String fileName = getFileName(filePath);
	    	//创建文件
        	File file = new File(fileName);
        	//创建字节流对象
        	OutputStream fos = new FileOutputStream(file, true);
        	//将数据写入文件
        	for (Object obj : list) {
        		fos.write((Integer) obj);
//        		//计算写入的进度
//                	String writePlan = getWriteFilePlan( file.length() , fileLength);
//                	//打印进度
//                	System.out.println(writePlan);
        	}
        	long time1 = System.currentTimeMillis();
        	System.out.println(fileName + "Byte  创建完成,耗时:" + (time1 - time) / 1000 + " 秒 ");
        
        	fos.close();
	}

	/**
	 * 读取文件多个字节 inputstream fileInputSream 字节流 常用于读二进制文件,如图片、声音、影像等文件
	 * @param filePath
	 * @throws Exception
	 */
	public static void readBytesByFileOprea(String filePath) throws Exception {
		InputStream fis = new FileInputStream(new File(filePath));
		// 创建集合存储读取的二进制文件
		List list = new ArrayList();
		byte[] b = new byte[5000];
		int len = -1;
		while ((len = fis.read(b)) != -1) {
//		    	System.out.println(new String(b, 0, len));
			list.add(len);
		}
		fis.close();
		// 如果list 为空,return ,不为空
		if (list.size() != 0) {
			writeBytesByFileOprea(filePath, list, b);
		} else {
			System.out.println("文件为空");
			return;
		}
	}

	/**
	 * 写文件多个字节 outputStream fileOutputSteram 字节流 常用于写二进制文件,如图片、声音、影像等文件
	 * @param filePath
	 * @param list
	 * @throws Exception
	 */
	public static void writeBytesByFileOprea(String filePath, List list,byte[] b) throws Exception {
	    	//获取文件名
	    	String fileName = getFileName(filePath);
		// 创建二进制文件写对象 并追加模式
		File file = new File(fileName);
		OutputStream fos = new FileOutputStream(file, true);
		// 遍历循环写操作
		for (Object obj : list) {
			fos.write(b, 0, (Integer) obj);
		}
		System.out.println(fileName + "bytes   创建完成");
		// 关闭流
		fos.close();
	}

	/**
	 * 获取文件的名称和 格式
	 * @param filePath		文件
	 * @return
	 */
	public static String getFileName(String filePath) {
		long date = System.currentTimeMillis();
		// 获取文件格式并转换成小写
		String fileBand = getFileBand(filePath);
		return "D:\\KuGou\\" + date + "." + fileBand;
	}

	// 获取文件格式
	public static String getFileBand(String filePath) {
		String[] str = filePath.split("\\.");
		return str[1];
	}
	/**
	 * 根据不同的文件类型执行不同的方法
	 * @param filePath
	 * @throws Exception
	 */
	public static void getFilePath(String filePath) throws Exception {
		String fileBand = getFileBand(filePath).toLowerCase();
		// 音频文件,视频文件,压缩文件
		if (fileBandList.contains(fileBand)) {
		    	//字节流方法
			readByteByFileOpera(filePath);
		} else {
		    	//字符流方法
			readCharsByFileOprea(filePath);
//			readBytesByFileOprea(filePath);
		}
	}
	/**
	 * 读取文件的进度
	 * @param readFile		读取文件的大小
	 * @param fileLength	源文件的大小
	 * @return
	 */
	public static String getReadFilePlan(long readFile , long fileLength){
	    DecimalFormat df=new DecimalFormat(".##");
	    double bai =readFile *10000 / fileLength;
	    String st = df.format(bai/100);
	    if(bai < 100){
		st = "读取进度:"+ "0"+st + "%";
	    }else{
		st = "读取进度:"+ st +"%";
	    }
		return st ;
	}
	/**
	 * 读取写入文件的进度
	 * @param writeFile		写入文件的大小
	 * @param fileLength	写入源文件的大小
	 * @return
	 */
	public static String getWriteFilePlan(long writeFile , long fileLength){
	    //格式化  保留两位小数
	    DecimalFormat df=new DecimalFormat(".##");
	    double bai =writeFile *10000 / fileLength;
	    String st = df.format(bai/100);
	    if(bai < 100){
		st = "写入进度:"+ "0"+st + "%";
	    }else{
		st = "写入进度:"+ st +"%";
	    }
	    return st;
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值