
与基于字节的流不同,在 java 中使用字符流进行文件 i/o 操作主要用于操作 unicode 文本。像 filereader 和 filewriter 这样的类可以方便地使用文本文件进行此操作。
使用 filewriter
filewriter 类允许您创建 writer 对象来写入文件。它的主要构造函数有:
filewriter(string nomearquivo) throws ioexception filewriter(string nomearquivo, boolean incluir) throws ioexception
下面是一个简单程序的示例,它从键盘读取文本行并将其写入名为“test.txt”的文件。阅读将继续,直到用户输入“停止”。
import java.io.*;
class KtoD {
public static void main(String args[]) {
String str;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter text ('stop' to quit).");
try (FileWriter fw = new FileWriter("test.txt")) {
do {
System.out.print(": ");
str = br.readLine();
if (str.compareTo("stop") == 0) break;
str = str + "\r\n"; // adiciona nova linha
fw.write(str);
} while (str.compareTo("stop") != 0);
} catch(IOException exc) {
System.out.println("I/O Error: " + exc);
}
}
}
在此示例中:
将 filewriter 与 bufferedreader 结合使用可以简化在文件中写入文本和操作数据,特别是在连续和国际化的文本操作中。
以上就是使用字符流进行文件 I/O的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号