import java.io.*; import org.junit.Test; public class FileReaderWriterTest { // 写 @Test public void testWriter() { FileWriter fw = null; try { // 1.实例化File类的对象,指明要写出到的文件 File file = new File("hello.txt"); // 2.提供FileWriter的对象,用于数据的写出 fw = new FileWriter(file); // 3.写出的操作 fw.write("I have a dream"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { if (fw != null) { // 4.关闭资源 try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } } } // 读 @Test public void testReader() { FileReader fr = null; try { // 1.实例化File类的对象,指明要操作的文件 File file = new File("hello.txt"); // 2.FileReader流的实例化 fr = new FileReader(file); // 3.1读数据 // read():返回读入的一个字符。如果文件末尾,返回-1 // int data; // while ((data = fr.read()) != -1) { // System.out.print((char)data); // } // 3.2读数据 char[] cbuf = new char[5]; int len; while ((len = fr.read(cbuf)) != -1) { for (int i = 0; i < len; i++) { System.out.print(cbuf[i]); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { if (fr != null) { // 4.关闭资源 try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } } // 读写 @Test public void testReaderWriter() { FileReader fr = null; FileWriter fw = null; try { File file1 = new File("hello.txt"); File file2 = new File("hello1.txt"); fr = new FileReader(file1); fw = new FileWriter(file2); // 读文件 char[] cbuf = new char[5]; int len; String str = ""; while ((len = fr.read(cbuf)) != -1) { str = new String(cbuf, 0, len); System.out.print(str); // 复制文件写出到file2 fw.write(str); } }catch (IOException e) { e.printStackTrace(); }finally { if (fw != null) { // 4.关闭资源 try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } if (fr != null) {// 加判断是防止空指针异常 // 4.关闭资源 try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
标签:fr,java,IO,fw,File,printStackTrace,读入,catch,new From: https://www.cnblogs.com/lxh-daniel/p/16710421.html