import java.awt.Frame; import java.io.*; public class filewriter { /** * @param args */ public static void main(String[] args) throws IOException{ // TODO Auto-generated method stub //test1(); test2(); } static void test1()throws IOException{ FileWriter fw = new FileWriter("F:\\fd.txt"); fw.write("sfasf"); fw.flush(); fw.write("zzzzz"); fw.flush(); fw.close(); fw = new FileWriter("F:\\fd.txt", true); fw.write("cccc"); fw.flush(); fw.close(); } static void test2(){ FileWriter fw = null; try { fw = new FileWriter("F:\\fd2.txt"); fw.write("wzz"); } catch (IOException e) { // TODO: handle exception System.out.println(e.toString()); } finally{ try { if(fw!=null) fw.close(); } catch (IOException e2) { // TODO: handle exception System.out.println(e2.toString()); } } } }
import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class filereader { /** * @param args */ public static void main(String[] args)throws IOException { // TODO Auto-generated method stub //test1() //test2(); //test3(); //test4(); test5(); } static void test1()throws IOException{ FileReader fr = new FileReader("F:\\fd.txt"); int c; while((c = fr.read()) != -1){ System.out.println((char)c); } fr.close(); } static void test2()throws IOException{ FileReader fr = new FileReader("F:\\fd.txt"); char[] buf = new char[3]; int x; while((x = fr.read(buf)) != -1){ System.out.println(buf); } fr.close(); } static void test3()throws IOException{ FileReader fReader = new FileReader("F:\\fd.txt"); char[] buf = new char[2]; int x; while((x = fReader.read(buf))!= -1){ System.out.print(new String(buf, 0, x)); } } static void test4()throws IOException{ FileWriter fw = new FileWriter("F:\\fd3.txt"); FileReader fr = new FileReader("F:\\fd2.txt"); int x; while((x = fr.read())!=-1) { fw.write(x); } fw.close(); fr.close(); } static void test5(){ FileWriter fw = null; FileReader fr = null; try { fw = new FileWriter("F:\\fd3.txt"); fr = new FileReader("F:\\fd2.txt"); int len = 0; char[] buf = new char[1024]; while((len = fr.read(buf)) != -1){ fw.write(buf, 0, len); } } catch (Exception e) { // TODO: handle exception System.out.println(e.toString()); } finally{ try { if(fw != null) fw.close(); } catch (IOException e2) { // TODO: handle exception System.out.println(e2.toString()); } try { if(fr!=null) fr.close(); } catch (IOException e2) { // TODO: handle exception System.out.println(e2.toString()); } } } }
FileWriter FileReader 文本的续写 文本的读取 文本的拷贝
IO FileWriter FileReader 学习
时间: 2024-11-03 00:49:50