使用文件字符输入流:
方法一:
FileInputStream.java
package filewriter;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;public class FileInputStream { public static void main(String[] args) { FileReader fr = null; try { 一次读取一个字符 fr = new FileReader(new File("D:/filewriter.txt")); int len = 0; while((len=fr.read())!=-1){ System.out.print((char)len); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(fr != null){ try { fr.close(); } catch (Exception e2) { e2.toString(); } } } }}
方法二:
package filewriter;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;public class FileInputStream { public static void main(String[] args) { FileReader fr = null; try { //将读取到的数据缓存到数组中,然后输出数组内的信息。 fr = new FileReader(new File("D:/filewriter.txt")); char buf [] = new char [1024]; int len = 0; while((len = fr.read(buf))!=-1){ System.out.println(new String (buf, 0, len)); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(fr != null){ try { fr.close(); } catch (Exception e2) { e2.toString(); } } } }}
文件字符输出流:
FileOutputStream.java
package filewriter;import java.io.File;import java.io.FileWriter;import java.io.IOException;public class FileOutputStream { public static void main(String[] args) { FileWriter fw = null; try { fw = new FileWriter(new File("D:/filewriter.txt"), true); String content = " I'm coming!FileWriter Studying!"; fw.write(content); fw.write("\r\n hello "); fw.flush(); } catch (Exception e) { e.toString(); }finally{ if(fw != null){ try { fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }}
带缓冲的文件字符输入流:
BufferedReader.java
package bufferedstream;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;public class BufferedReader { public static void main(String[] args) throws IOException { FileReader fr = new FileReader(new File("D:/buffered.txt")); java.io.BufferedReader br = new java.io.BufferedReader(fr); String content = null; while ((content = br.readLine()) != null) { System.out.println(content); } br.close(); }}
带缓冲的文件字符输出流:
package bufferedstream;import java.io.File;import java.io.FileWriter;import java.io.IOException;public class BufferedWriter { public static void main(String[] args) throws IOException { //true表明可以连续追加内容的字符输出流 FileWriter fw = new FileWriter(new File("D:/buffered.txt"),true); java.io.BufferedWriter bw = new java.io.BufferedWriter(fw); String content = "BufferedWriter,I'm coming!"; String contents = "BufferedWriter!"; bw.write(content); bw.newLine(); bw.write(contents); bw.flush(); bw.close(); }}