简体   繁体   English

在Java中打开文件后会发生什么

[英]what happens after opening files in java

suppose that using a JFilechooser , we choosed a text file which contained 1 line , say... "hello world" 假设使用JFilechooser,我们选择了一个文本文件,其中包含1行,例如...“ hello world”

File file = new File("someFile.txt")

when we print the file contents we get "hello world" but what happens if we changed the text file contents and added some new lines , and printed again , does java stores the file in memory ? 当我们打印文件内容时,会出现"hello world"但是如果我们更改文本文件内容并添加一些新行并再次打印,java将文件存储在内存中怎么办? or it will reads it again , and consequently prints the new lines we added ? 还是它将再次读取它,并因此打印我们添加的新行?

That depends on what you do. 那要看你做什么。 The rules are simple: when you read it again by using a FileInputStream or a FileReader , you will always get the latest content. 规则很简单:使用FileInputStreamFileReader再次阅读时,您将始终获得最新的内容。 The OS might optimize this in memory, if the file is not edited. 如果未编辑文件,则操作系统可能会在内存中对此进行优化。 If you simply keep the file contents into a self constructed buffer (eg: a String or a byte[] ), and the file changes, of course the buffer will remained unchanged. 如果仅将文件内容保留在自构造缓冲区中(例如: Stringbyte[] ),并且文件发生更改,则缓冲区当然将保持不变。

When you create a File , nothing actually happens. 创建File ,实际上什么也没有发生。 The location of the file is stored, nothing else. 文件的位置已存储,仅此而已。 It's like setting your GPS to go somewhere versus driving there. 这就像将GPS设置到某处而不是在那儿开车一样。

From the Javadoc: 从Javadoc:

An abstract representation of file and directory pathnames. 文件和目录路径名的抽象表示。

When you read from the file, you'll get the contents of the file. 从文件中读取时,您将获得文件的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM