Java IO 流,读写取文件操作方法

 

/**
 * 
 */
/**
 * @author WangBenYan
 *
 */
package File;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Date;

public class FileDemo {

	/* 以字符流读取文件 */
	public void readFile(String filePath) {
		File file = new File(filePath);
		InputStream input = null;
		BufferedReader buffReader = null;
		try {
			input = new FileInputStream(file);
			InputStreamReader reader = new InputStreamReader(input);
			buffReader = new BufferedReader(reader);
			String tempLine = null;
			while ((tempLine = buffReader.readLine()) != null) {
				System.out.println(tempLine);
			}
			input.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	/*以字节的形式读取 文件*/
	public void readFileBybyte(String filePath) {
		File file = new File(filePath);
		BufferedInputStream inputStream = null;
		byte[] buffer = new byte[1024];
		try {
			InputStream input = new FileInputStream(file);
			inputStream = new BufferedInputStream(input);
			int temp = 0;
			while ((temp = inputStream.read(buffer)) != -1) {
				// 将读取的字节转为字符串对象
				String chunk = new String(buffer, 0, temp);
				System.out.print(chunk);
			}
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			// 关闭 BufferedInputStream
			try {
				if (inputStream != null)
					inputStream.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}
	public static void writeTxtFile(String content) {
		BufferedWriter buff = null;
		try {
			File file = new File("d:\\test.txt");
			if (!file.exists()) {
				file.createNewFile();
			}
			FileWriter fw = new FileWriter(file.getAbsolutePath());
			buff = new BufferedWriter(fw);
			System.out.println("正在写入内容到文件中,内容:" + content);
			buff.write(content);
			buff.close();
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		}

	}
	/*以字符的形式读取文件*/
	public static String readTxtFile(String path) {
		StringBuilder content = new StringBuilder("");
		try {
			String encoding = "utf-8";
			File file = new File(path);
			if (file.isFile() && file.exists()) {
				InputStreamReader input = new InputStreamReader(new FileInputStream(file), encoding);
				BufferedReader bufferReader = new BufferedReader(input);
				String lineTxt = null;
				System.out.println("开始读取文件内容:");
				while ((lineTxt = bufferReader.readLine()) != null) {
					String[] result = getNamePhone(lineTxt);
					System.out.println(lineTxt);
					content.append(result[0] + "-----" + result[1]);
					content.append("\r\n");
				}
				input.close();

			} else {
				System.out.println("系统找不到指定的文件");
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("读取文件内容出错");
			e.printStackTrace();
		}

		return content.toString();
	}

	public static String[] getNamePhone(String str) {
		String[] result = new String[2];
		int index = 0;
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
				index = i;
				break;
			}
		}
		result[0] = str.substring(0, index);
		result[1] = str.substring(index);
		return result;
	}

	// 字符流读写文件方法 InputStream、outputStream
	// BufferedInputStream 、BufferedOutputStream (缓存字节流)使用方式和字节流差不多,但是效率更高(推荐使用)
	// InputStreamReader、OutputStreamWriter(字节流,这种方式不建议使用,不能直接字节长度读写)。使用范围用做字符转换
	// BufferedReader、BufferedWriter(缓存流,提供readLine方法读取一行文本)
	// Reader、PrintWriter(PrintWriter这个很好用,在写数据的同时可以格式化)
	/*
	 * 字节流与字符流 字节流的操作:
	 * 
	 * 1)输入:inputStream、FileInputStream/FilterIuptSteam、BufferedInputStream
	 * 
	 * 2)输出:outPutStream、FileOutputStream/FilterOutputStream、BufferdeOutputStream
	 * 
	 * 字符流的操作:
	 * 
	 * 1)输入主要使用:write类、BufferedWrite/OutputSteamWrite、FileWrite。
	 * 
	 * 2)输出主要使用:reader类、BufferedReader/InputSteamReader、FileReader。
	 * 
	 * 内容操作就四个类。
	 */
	public static String InputToWriteFile(String path) {
		File file = new File(path);
		InputStream input = null;
		try {
			if (file.isFile() && file.exists()) {
				input = new FileInputStream(file);
				byte b[] = new byte[1024];
				int len = 0;
				int temp = 0;
				while ((temp = input.read()) != -1) {
					b[len] = (byte) temp;
					len++;
				}
				System.out.println("读取文件内容为:" + new String(b, 0, len)); // 把byte数组变为字符串输出
			}
			input.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "Success";
	}

	public static void OutputToFile(String path) {
		File file = new File(path);
		OutputStream output = null;
		if (file.isFile() && file.exists()) {
			try {
				output = new FileOutputStream(file);
				String str = "hello word! 您好!";
				byte[] b = str.getBytes();
				// 将字符转换成字节输出保存
				output.write(b);
				System.out.println("写入到文件中,写入内容:" + str);
				output.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}


	public static void main(String[] args) {

		/**************** 获取开始时间 ****************/
		long t1 = System.currentTimeMillis();
		String filePath = "e:\\AB.txt";
		FileDemo fileDemo = new FileDemo();
		/*方法一*/
		// fileDemo.readFile(filePath);
		/*方法二*/
		fileDemo.readFileBybyte(filePath);
		/***********************************/
		System.out.println("----------------------");
		System.out.println("IO 读取文件 ---> ");
		// 使用io读写相间到文件中
		// 写入文件中内容
		String[] name = getNamePhone("xiaoxiaoniao0123456789");
		for (String str : name) {
			writeTxtFile(str);
		}
		Date date = new Date();
		date.getTime();
		System.out.println("{}" + date.getTime());
		// 文件存放地址
		String path = "d:\\test.txt";
		readTxtFile(path);
		String status = InputToWriteFile(path);
		System.out.println(status);
		OutputToFile(path);
		/**************** 获取结束时间 ****************/
		long t2 = System.currentTimeMillis();
		System.out.println("\n耗时:" + (t2 - t1)); // 时间差

	}

}

 

 


1、流的分类

按照数据方向分:输入流和输出流;

输入流:InputStream / Reader

输出流:OutputStream /Writer

按照数据类型分:字节流和字符流;

字节流:InputStream / outputStream

字符流:Reader / Writer

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值