到目前为止,我一直在使用Scanners 从文本文件中读取数据。例子:
File file = new File("path\\to\\file") ;
Scanner scan = new Scanner(file) ;
System.out.println(scan.nextLine()) ;
Run Code Online (Sandbox Code Playgroud)
并使用FileWriters 将数据写入文本文件。像这样:
try
{
FileWriter writer = new FileWriter("Foo.txt") ;
writer.write("hello there!") ;
writer.close()
}
catch(IOException ex)
{
ex.printStackTrace() ;
}
Run Code Online (Sandbox Code Playgroud)
几天前,我和我的导师开会。当我检查他的代码,我注意到他曾使用BufferedReader和BufferedWriter-的读取和写入文件,我以前没有使用过的方法。然后我问他使用 aBufferedReader和 aScanner从文件中读取数据有什么区别。他无法向我解释。
所以我做了一些研究,发现隐藏在引擎盖下执行这些操作的类是InputStream和OutputStream。这些类都有各自喜欢的子类FileInputStream,FileOutputStream等等。
在我的进一步研究中,我遇到了用于从文件读取数据和将数据写入文件的Reader和Writer类。同样,与InputStreamand 一样OutputStream,这些类都是abstract super类,并且有自己的子类来执行读写操作。
我对此并不感到困惑,但是......为什么?我的意思是,为什么有不同的方法来做同样的事情?有什么意义?哪种方法是处理文件输入和输出的最有效方法?