本文共 2544 字,大约阅读时间需要 8 分钟。
字符流在Java程序中用于处理文本数据的读取和写入,Writer和Reader类为字符流提供了基本操作接口。本文将详细介绍Writer和Reader的使用方法,以及字节流与字符流的区别。
Writer类是Java用于字符流输出的核心类,主要用于向文件或其他输出设备中写入文本数据。
使用Writer类操作文件,流程与字节流操作类似,但更加简便。
import java.io.File;import java.io.FileWriter;public class Root { public static void main(String[] args) throws Exception { File f = new File("D:" + File.separator + "test.txt"); FileWriter out = new FileWriter(f); String str = "Hello World !!!"; out.write(str); out.close(); }}
FileWriter支持动态追加文件内容,可通过第二个参数true
开启追加模式。
public class Root { public static void main(String[] args) throws Exception { File f = new File("D:" + File.separator + "test.txt"); FileWriter out = new FileWriter(f, true); String str = "\r\n Java Hello World !!!"; out.write(str); out.close(); }}
Reader类用于从字符流中读取文本数据,主要用于文件的字符读取操作。
使用Reader类可以直接读取字符,适用于文本文件的处理。
import java.io.File;import java.io.FileReader;public class Test { public static void main(String[] args) throws Exception { File f = new File("D:" + File.separator + "test.txt"); FileReader reader = new FileReader(f); char[] c = new char[1024]; int len = reader.read(c); System.out.println("内容为:" + new String(c, 0, len)); reader.close(); }}
当不知道文件长度时,可以使用循环读取字符。
char[] c = new char[1024];int len = 0;int temp = 0;while ((temp = reader.read()) != -1) { c[len++] = (char) temp;}System.out.println("内容为:" + new String(c, 0, len));reader.close();
字符流在读取或写入时会使用内置缓冲区,提高读写效率,而字节流直接操作文件,不使用缓冲区。
这种方法适用于大文件复制,避免占用过多内存。
import java.io.*;public class Copy { public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println("输入的参数不正确!"); System.exit(1); } File f1 = new File(args[0]); File f2 = new File(args[1]); if (!f1.exists()) { System.out.println("源文件不存在!"); System.exit(1); } InputStream input = new FileInputStream(f1); OutputStream out = new FileOutputStream(f2); while ((temp = input.read()) != -1) { out.write(temp); } System.out.println("复制完成"); input.close(); out.close(); }}
通过以上方法,可以高效地完成文件复制任务。字符流的边读边写方式在处理大文件时表现更优,避免了内存过载问题。
转载地址:http://fixr.baihongyu.com/