java读取文件的基本操作

import java.io.FileInputStream;

/**
 * 使用FileInputStream读取文件
 */
public class FileRead {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// 读取文件操作

		// 1.通过 fis.read()方法读取,一个字节一个字节读取,对数据进行循环遍历
		// ReadFileToint();
		// 2.通过fis.read(data,0,length)方法读取。把数据一次全部读到data字节数组里面
		ReadFile();
	}

	public static void ReadFileToint() {
		// 声明流对象
		FileInputStream fis = null;
		try {
			// 创建流对象
			fis = new FileInputStream("d:\\test\\a.txt");
			// 读取数据,并将读取到的数据存储到数组中
			byte[] data = new byte[1024]; // 数据存储的数组
			int i = 0; // 当前下标
			// 读取流中的第一个字节数据
			int n = fis.read();
			// 依次读取后续的数据
			while (n != -1) { // 未到达流的末尾
				// 将有效数据存储到数组中
				data[i] = (byte) n;
				// 下标增加
				i++;
				// 读取下一个字节的数据
				n = fis.read();
			}

			// 解析数据
			String s = new String(data, 0, i);
			// 输出字符串
			System.out.println(s);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭流,释放资源
				fis.close();
			} catch (Exception e) {
			}
		}
	}

	public static void ReadFile() {
		// 声明流对象
		FileInputStream fis = null;
		try {
			// 创建流对象
			fis = new FileInputStream("d:\\test\\a.txt");
			// 读取数据,并将读取到的数据存储到数组中
			byte[] data = new byte[1024]; // 数据存储的数组
			int i = fis.read(data);

			// 解析数据
			String s = new String(data, 0, i);
			String[] ssStrings = s.split("\r\n");
			for (String b : ssStrings) {
				System.out.println(b.replace('|', ' '));
			}
			// 输出字符串
			System.out.println(s);

			/*
			 * 其实懂正则表达式的应该已经发现了,是的,“.”是正则表达式的元字符,匹配除换行符以外的任意字符,所以replaceAll、
			 * replaceFirst才出现了这样的结果。
			 * 
			 * 而replace没有用到正则表达式,但会把所有“.”替换掉,很多人可能会误解replace是替换单个,而replaceAll是替换全部
			 * ,其实这是错的(我以前也是这么想的- -)。replace只是没有用到正则表达式,但会替换所有匹配的字符串。
			 * 到这里一些不懂正则表达式的小伙伴可能就要喊坑爹了
			 * ,“那我不想用正则表达式去替换第一个字符串肿么办?”其实也很简单,只要将元字符串转义就行了
			 * 。s.replaceFirst("\\.", "#")
			 */

			/*
			 * 这里给个会被正则表达式识别的字符列表: .匹配除换行符以外的任意字符 ^匹配字符串的开始 $匹配字符串的结束* 重复零次或更多次
			 * +重复一次或更多次 ?重复零次或一次
			 */
			String ss = "my.test.txt";
			String[] myStrings = ss.split("\\.", 2);
			for (String b : myStrings) {
				System.out.println(b);
			}
			System.out.println(ss.replace(".", "#"));
			System.out.println(ss.replaceAll(".", "#"));
			System.out.println(ss.replaceFirst(".", "#"));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭流,释放资源
				fis.close();
			} catch (Exception e) {
			}
		}
	}
}

  

posted @ 2016-02-16 09:50  程序员中的华仔  阅读(1308)  评论(0编辑  收藏  举报