* 使用FileReader、FileWriter 可以实现文本文件的复制。
* 对于非文本文件(视频文件、音频文件、图片),只能使用字节流!
1 @Test 2 public void testFileReader(){ 3 FileReader fr = null; 4 try { 5 File file = new File("dbcp.txt"); 6 fr = new FileReader(file); 7 char[] c = new char[24]; 8 int len; 9 while((len = fr.read(c)) != -1){ 10 String str = new String(c, 0, len); 11 System.out.print(str); 12 } 13 }catch (IOException e) { 14 // TODO Auto-generated catch block 15 e.printStackTrace(); 16 }finally{ 17 if(fr != null){ 18 try { 19 fr.close(); 20 } catch (IOException e) { 21 // TODO Auto-generated catch block 22 e.printStackTrace(); 23 } 24 } 25 } 26 27 }
1 @Test 2 public void testFileReaderWriter(){ 3 //1.输入流对应的文件src一定要存在,否则抛异常。输出流对应的文件dest可以不存在,执行过程中会自动创建 4 FileReader fr = null; 5 FileWriter fw = null; 6 try{ 7 //不能实现非文本文件的复制 8 // File src = new File("C:\\Users\\shkstart\\Desktop\\1.jpg"); 9 // File dest = new File("C:\\Users\\shkstart\\Desktop\\3.jpg"); 10 File src = new File("dbcp.txt"); 11 File dest = new File("dbcp1.txt"); 12 //2. 13 fr = new FileReader(src); 14 fw = new FileWriter(dest); 15 //3. 16 char[] c = new char[24]; 17 int len; 18 while((len = fr.read(c)) != -1){ 19 fw.write(c, 0, len); 20 } 21 }catch(Exception e){ 22 e.printStackTrace(); 23 }finally{ 24 if(fw != null){ 25 try { 26 fw.close(); 27 } catch (IOException e) { 28 // TODO Auto-generated catch block 29 e.printStackTrace(); 30 } 31 } 32 if(fr != null){ 33 try { 34 fr.close(); 35 } catch (IOException e) { 36 // TODO Auto-generated catch block 37 e.printStackTrace(); 38 } 39 } 40 } 41 }