读取文件代码如下:
package com.java.day23FileReader; import java.io.FileReader; import java.io.IOException; public class RederFile { public static void main(String[] args) { readFile(); } public static void readFile() { FileReader fr = null; try { fr = new FileReader("D:\\IdeaProjects\\StudyJava\\day01\\src\\com\\java\\day23FileReader\\test01"); int len = 0; while ((len = fr.read()) != -1) { System.out.print((char) len); } } catch (IOException e) { e.printStackTrace(); } finally { if (fr != null) { try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
效果如图:
写入文件代码如下:
package com.java.day25FileWrite; import java.io.FileWriter; import java.io.IOException; public class WriteFile { public static void main(String[] args) { fileWrite(); } public static void fileWrite() { FileWriter fw = null; try { fw = new FileWriter("D:\\IdeaProjects\\StudyJava\\day01\\src\\com\\java\\day25FileWrite\\test01.txt",true); fw.write("Hello世界"+"\r\n"); } catch (IOException e) { e.printStackTrace(); } finally { if (fw != null) { try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
运行效果如图: