扫描仪类在以下代码中如何与FileReader进行交互?
try{
PrintWriter pW = new PrintWriter("newFile.txt");
pW.println("Hello");
pW.print("My name is Julian");
pW.println("");
pW.print("This is the third line");
pW.close();
FileReader fR = new FileReader("newFile.txt");
Scanner scan = new Scanner(fR);
System.out.println(scan.nextLine());
System.out.println(scan.nextLine());
System.out.println(scan.nextLine());
}catch(Exception ex){
}
到目前为止,我已经了解到,fileReader对象可以使用“读取”方法将文件从文件读取到字符数组中。
但是,在上面的代码中,扫描仪对象将fileReader对象作为其构造函数的参数。可以说是在说明system.out.uot.println(scan.nextline());执行?扫描仪对象如何从FileReader对象“获取”数据?
要概念化发生的事情“引擎盖下”,我想扫描仪对象的缓冲区类似于数组。因此,在引擎盖下将发生的事情本质上是fileReader对象的读取方法,并且传递的参数将是扫描仪对象缓冲区(例如filereaderobject.read(scannerobject.scannerobject.scannerobjectbuffer)。因此,文件中的数据将是文件的数据阅读扫描仪对象缓冲区,我们可以使用下一个/Nextline方法来获取此数据。 兜帽?
try{
PrintWriter pW = new PrintWriter("newFile.txt");
pW.println("Hello");
pW.print("My name is Julian");
pW.println("");
pW.print("This is the third line");
pW.close();
FileReader fR = new FileReader("newFile.txt");
Scanner scan = new Scanner(fR);
System.out.println(scan.nextLine());
System.out.println(scan.nextLine());
System.out.println(scan.nextLine());
}catch(Exception ex){
}
Thus far, I have understood that a fileReader object can use the "read" method to read data from a file into an array of characters.
However, in the above code, the Scanner object takes the fileReader object as an argument to its constructor. What is going on "under the hood" so to speak when the statement System.out.println(scan.nextLine()); is executed? How does the Scanner object "obtain" data from the fileReader object?
To conceptualize whats going on "under the hood" I imagine the Scanner object's buffer is similar to an array. Thus, what will happen under the hood is essentially the fileReader object's read method will be called, and the argument passed will be the Scanner objects buffer(something like fileReaderobject.read(Scannerobject.Scannerobjectbuffer) . Thus, the data from the file will be read into Scanner objects buffer, and we can use the next/nextLine methods to obtain this data. Is this a somewhat correct way of conceptualizing what is happening under the hood?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
FileReader只是一个读者,因此Scanner可能使用
read()
方法来读取行。这样的事情:FileReader is just a Reader, so Scanner likely uses the
read()
method to read a line. Something like this: