1.FileReader/FileWriter读写文本文件
直接使用读写器进行读写。
@Test public void testFileReader(){ try { File file = new File("test1.txt"); File file1 = new File("test2.txt"); FileReader fr = new FileReader(file); FileWriter fw = new FileWriter(file1); int len = 0; while ((len = fr.read()) !=-1) { System.out.println("ASCII:"+len+","+"numValue :"+(char)len); fw.write(len); } } //输出ASCII与对应的字符值 }
2.BufferedReader/BufferedWriter文件读写与复制
在读写器外面包装了缓冲流。
@Test public void testBufferedReader(){ BufferedReader br = null; BufferedWriter bw = null; try { File file = new File("test1.txt"); File file1 = new File("test20.txt"); FileReader fr = new FileReader(file); FileWriter fw = new FileWriter(file1); br = new BufferedReader(fr); bw = new BufferedWriter(fw); -------------------第一种方式-------------------------- // char[] c = new char[1024]; // int len; // while((len = br.read(c))!= -1){ // String str = new String(c, 0, len); // System.out.print(str); // } ------------------第二种方式------------------------------ String str; while((str = br.readLine()) != null){ System.out.println(str); bw.write(str + "\n"); // bw.newLine();//与上面效果相同,换行 bw.flush(); } }catch (IOException e) { e.printStackTrace(); }finally{ if(bw != null){ try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } if(br != null){ try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } }