根據給定的 File 對象構造一個 FileWriter 對象
public FileWriter(File file)throws IOException根據給定的文件名構造一個 FileWriter 對象
public FileWriter(String fileName)throws IOException實例01: package cn.itcast04; import java.io.FileWriter; import java.io.IOException; public class FileWriterDemo01 { public static void main(String[] args) throws IOException { //創建IO對象 FileWriter fw = new FileWriter("d.txt" ); String s = "I love JAVA"; //寫入字符串 fw.write( "Hello World"); //寫入字符串的一部分 fw.write(s, 1,5); //寫入字符數組 char[] chars = new char[]{ 'a', 'c', 'b', 'e'}; fw.write(chars); //寫入字符數組的一部分 fw.write(chars,0,3); fw.close(); } }
字符輸入流(Reader) API文檔介紹(Reader): public abstract class Reader extends Object implements Readable, Closeable FileReader類常用方法: 構造方法: 根據給定的 File 對象構造一個 FileWriter 對象 public FileReader(File file)throws IOException 根據給定的文件名構造一個 FileWriter 對象 public FileReader(String fileName)throws IOException 常用方法: 讀取單個字符: public int read()throws IOException 將字符讀入數組 public int read(char[] cbuf)throws IOException 讀取數組中的一部分 public abstract int read(char[] cbuf,int off,int len)throws IOException
實例02: package cn.itcast04; import java.io.File; import java.io.FileReader; import java.io.IOException; public class FileReaderDemo01 { public static void main(String[] args) throws IOException { File file= new File("d.txt" ); FileReader fr = new FileReader(file); //讀取單個字符 int c; while((c=fr.read())!=-1) { System. out.println((char)c); } fr.close(); System. out.println("================================" ); File file2= new File("d.txt" ); FileReader fr2 = new FileReader(file2); //讀入一個數組 char[] chars = new char[( int)file2.length()]; int len; while((len=fr2.read(chars))!=-1) { String s = new String(chars,0,len); System. out.println(s); } fr2.close(); } }