“你好,阿米戈!昨天,里希给你介绍了 FileInputStream 和 FileOutputStream。今天,我要给你讲解 FileReader 和 FileWriter 类。”
你可能已经猜到了,所有这些类都是 File 对象与 InputStream、OutputStream、Reader 和 Writer“接口”之间的适配器。
“它们类似于 File 和 Reader/Writer 之间的适配器,但你只需将 String 对象传递给构造方法,而不是 File!”
“实际上,它们包含几个构造方法。File 和 String 对象都有构造方法。如果将 String 对象传递给构造方法,则构造方法将使用从所传递的 String 对象获取的文件路径来悄悄地创建 File 对象。”
这是为了提供方便。Java 创建者选取了这些类的最常见用例,并为所有这些用例编写了构造方法。这是非常方便的,你不觉得吗?
“哦,是的。非常方便。我同意。但是为什么我必须不断写入:”
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
“他们为什么不添加此用例?”
“问题在于,典型的 Java 程序不使用控制台。实际上,你几乎从不在控制台上读取任何内容。即使使用 Web 服务器、应用程序服务器或某些其他复杂的系统。”
但是,我们确实有用于将数据和文本输出到控制台的 PrintStream。因为这些“服务器应用程序”确实经常使用控制台来显示其状态、错误以及各种其他信息。
“明白了。你还可以使用 FileReader 和 FileWriter 复制文件吗?”
“可以,如果文件是文本文件(即文件由字符组成)。下面是一个示例:”
public static void main(String[] args) throws Exception
{
FileReader reader = new FileReader("c:/data.txt");
FileWriter writer = new FileWriter("c:/result.txt");
while (reader.ready()) //as long as there are unread bytes in the input stream
{
int data = reader.read(); //Read one character (the char will be widened to an int)
writer.write(data); //Write one character (the int will be truncated/narrowed to a char)
}
//Close the streams after we done using them
reader.close();
writer.close();
}
“几乎没有任何不同。”
“是的,差别极小。”
GO TO FULL VERSION