标签:
java的文件读写有多种方式,在此通过代码做以下比较。
比较一:FileWriter和FileReader
public class MyCode1 { public static void main(String[] args) throws IOException { File f = new File("my.txt"); FileWriter fw = new FileWriter(f); fw.write("HELLO"); fw.close(); FileReader fr = new FileReader(f); System.out.println((char)fr.read()); fr.close(); } }
输出: H
可见,FileWriter可以批量写入,但是FileReader每次只能读取一个字符。
比较二:OutputStream和InputStream
public class MyCode1 { public static void main(String[] args) throws IOException { File f = new File("my.txt"); char[] data = new char[]{‘H‘, ‘E‘, ‘L‘, ‘L‘, ‘O‘}; OutputStream os = new FileOutputStream(f); os.write(data[0]); os.close(); InputStream is = new FileInputStream(f); System.out.println((char)is.read()); is.close(); } }
输出: H
可见,OutputStream和InputStream每次只可以读写一个字符。
比较三:OutputStreamWriter和InputStreamReader
public class MyCode1 { public static void main(String[] args) throws IOException { File f = new File("my.txt"); OutputStream os = new FileOutputStream(f); OutputStreamWriter osw = new OutputStreamWriter(os); osw.write("HELLO"); osw.close(); os.close(); InputStream is = new FileInputStream(f); InputStreamReader isr = new InputStreamReader(is); System.out.println((char)isr.read()); isr.close(); is.close(); } }
输出: H
可见,OutputStreamWriter可以批量写入,但是InputStreamReader每次只能读取一个字符。效果同FileWriter和FileReader。
比较四:BufferedWriter和BufferedReader
public class MyCode1 { public static void main(String[] args) throws IOException { File f = new File("my.txt"); OutputStream os = new FileOutputStream(f); OutputStreamWriter osw = new OutputStreamWriter(os); BufferedWriter bw = new BufferedWriter(osw); bw.write("HELLO"); bw.close(); osw.close(); os.close(); InputStream is = new FileInputStream(f); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); System.out.println(br.readLine()); isr.close(); is.close(); } }
输出: HELLO
可见,BufferedWriter和BufferedReader可以批量读写。
java的inputstream, outputstream, reader和writer的比较
标签:
原文地址:http://www.cnblogs.com/onmyway227/p/5397768.html