package com.baoge.test; 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.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Date; import java.util.Random; public class Test1 { public static void main(String[] args) throws IOException { File file = new File("D://test.txt"); writeFile(file); readFile(file); } public static void writeFile(File file) throws IOException{ //1m=1024kb , 1kb = 1024byte,gbk编码中一个英文字符占一个字节。 int fileSize = 500*1024*1024; BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))); Random random = new Random(); System.out.println("start time="+new Date()); int i = 0; while( i < fileSize ){ int num = random.nextInt(26);//生成随机数,大于等于0,小于26 char c = (char) (num+97);//a:97,b:98.....,z:122 bw.write(""+c); i ++; } bw.flush(); bw.close(); System.out.println("end time="+new Date()); } public static void readFile(File file) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); int index = 0; int count = 0; char[] chars = new char[3]; while(br.read(chars, 0, 3)>-1){ String str = new String(chars); if(str.equals("abc")){ count ++; System.out.println("数量:"+count+"---位置:"+index); } index += 3; } br.close(); } }