java编程
一、
1 import java.io.FileReader; 2 import java.io.FileWriter; 3 import java.io.IOException; 4 /* 5 * 需求:将c盘的一个文本文件复制到d盘。 6 * 7 * 思路: 8 * 1,需要读取源, 9 * 2,将读到的源数据写入到目的地。 10 * 3,既然是操作文本数据,使用字符流。 11 * 12 */ 13 public class CopyTextTest { 14 /** 15 * @param args 16 * @throws IOException 17 */ 18 public static void main(String[] args) throws IOException { 19 //1,读取一个已有的文本文件,使用字符读取流和文件相关联。 20 FileReader fr = new FileReader(“IO流_2.txt”); 21 //2,创建一个目的,用于存储读到数据。 22 FileWriter fw = new FileWriter(“copytext_1.txt”); 23 //3,频繁的读写操作。 24 int ch = 0; 25 while((ch=fr.read())!=-1){ 26 fw.write(ch); 27 } 28 //4,关闭流资源。 29 30 fw.close(); 31 fr.close(); 32 } 33 } 34 35 2.以下是借助了数组,即缓冲区,并进行了异常处理 36 import java.io.FileReader; 37 import java.io.FileWriter; 38 import java.io.IOException; 39 public class CopyTextTest_2 { 40 private static final int BUFFER_SIZE = 1024; 41 /** 42 * @param args 43 */ 44 public static void main(String[] args) { 45 FileReader fr = null; 46 FileWriter fw = null; 47 try { 48 fr = new FileReader(“IO流_2.txt”); 49 fw = new FileWriter(“copytest_2.txt”); 50 51 //创建一个临时容器,用于缓存读取到的字符。 52 char[] buf = new char[BUFFER_SIZE];//这就是缓冲区。 53 54 //定义一个变量记录读取到的字符数,(其实就是往数组里装的字符个数 ) 55 int len = 0; 56 57 while((len=fr.read(buf))!=-1){ 58 fw.write(buf, 0, len); 59 } 60 61 } catch (Exception e) { 62 // System.out.println(“读写失败”); 63 throw new RuntimeException(“读写失败”); 64 }finally{ 65 if(fw!=null) 66 try { 67 fw.close(); 68 } catch (IOException e) { 69 70 e.printStackTrace(); 71 } 72 if(fr!=null) 73 try { 74 fr.close(); 75 } catch (IOException e) { 76 77 e.printStackTrace(); 78 } 79 } 80 } 81 }
二、
1 import java.io.BufferedReader; 2 import java.io.FileReader; 3 import java.util.regex.Matcher; 4 import java.util.regex.Pattern; 5 6 public class TxtCount { 7 8 /** 9 * @param args 10 */ 11 public static void main(String[] args) throws Exception { 12 BufferedReader br = new BufferedReader(new FileReader("C:\\test.txt")); 13 StringBuilder sb = new StringBuilder(); 14 while (true) { 15 String str = br.readLine(); 16 if (str == null) 17 break; 18 sb.append(str); 19 } 20 Pattern p = Pattern.compile("mobnet"); 21 Matcher m = p.matcher(sb); 22 int count = 0; 23 while(m.find()) { 24 count++; 25 } 26 System.out.println("mobnet一共出现了" + count + "次"); 27 } 28 29 }

浙公网安备 33010602011771号