本笔记来源于 :尚硅谷Java零基础全套视频教程(宋红康2023版,java入门自学必备)b站视频
1.FileReader/FileWriter的使用: 1.1 FileReader的使用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 @Test public void testFileReader1 () { FileReader fr = null ; try { File file = new File ("hello.txt" ); fr = new FileReader (file); char [] cbuf = new char [5 ]; int len; while ((len = fr.read(cbuf)) != -1 ){ String str = new String (cbuf,0 ,len); System.out.print(str); } } catch (IOException e) { e.printStackTrace(); } finally { if (fr != null ){ try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } }
1.2 FileWriter的使用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 @Test public void testFileWriter () { FileWriter fw = null ; try { File file = new File ("hello1.txt" ); fw = new FileWriter (file,false ); fw.write("I have a dream!\n" ); fw.write("you need to have a dream!" ); } catch (IOException e) { e.printStackTrace(); } finally { if (fw != null ){ try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
1.3 文本文件的复制: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 @Test public void testFileReaderFileWriter () { FileReader fr = null ; FileWriter fw = null ; try { File srcFile = new File ("hello.txt" ); File destFile = new File ("hello2.txt" ); fr = new FileReader (srcFile); fw = new FileWriter (destFile); char [] cbuf = new char [5 ]; int len; while ((len = fr.read(cbuf)) != -1 ){ fw.write(cbuf,0 ,len); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (fw != null ) fw.close(); } catch (IOException e) { e.printStackTrace(); } try { if (fr != null ) fr.close(); } catch (IOException e) { e.printStackTrace(); } } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 * 1. 对于文本文件(.txt,.java,.c,.cpp),使用字符流处理 * 2. 对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,...),使用字节流处理@Test public void testFileInputOutputStream () { FileInputStream fis = null ; FileOutputStream fos = null ; try { File srcFile = new File ("爱情与友情.jpg" ); File destFile = new File ("爱情与友情2.jpg" ); fis = new FileInputStream (srcFile); fos = new FileOutputStream (destFile); byte [] buffer = new byte [5 ]; int len; while ((len = fis.read(buffer)) != -1 ){ fos.write(buffer,0 ,len); } } catch (IOException e) { e.printStackTrace(); } finally { if (fos != null ){ try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null ){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
【注意】 相对路径在IDEA和Eclipse中使用的区别?IDEA: 如果使用单元测试方法,相对路径基于当前的Module的。 如果使用main()测试,相对路径基于当前Project的。
Eclipse: 单元测试方法还是main(),相对路径都是基于当前Project的。