2

When you make a File object instance in a java program, is it possible for a concurrently running program to also have access to the file for writing? So like if I had a File object with a path to example.txt, can another program be writing in that example.txt file while I have my File object existing?

4 Answers 4

3

Doing

File f = new File("C:\\test.txt");

does nothing to the file. So any other thread or process can open the file if they like.

It just creates an object that represents the file, but doesn't open it or otherwise touch it.

Sign up to request clarification or add additional context in comments.

2 Comments

so when another program is writing to example.txt, the canRead method will return false right and then when it's free, it'll return true?
@Andrew: Probably not. It depends on your file system, but as far as I know Linux, Mac and Windows (i.e. ext* and ntfs) do not prevent reads while another process has a file open for writing. If you really want file locking then you need to use the java.nio.channels.FileLock class.
3

IF you have written,

 File f=new File("example.txt");

that means, you only created a file object, but not created a file on your harddisk according to a given path.Also that file object is in virtual memory(Java).If any other application which has already loaded in virtual memory can access or call the file object's reference ,then that application can access the file object.
If you create a file with,

f.createNewFile();

Then there is a real file in your hard disk.Then any other application can access it as other files in your hard disk. Would you have see here

Comments

1

Yes, because a File object in Java really just represents a file system path. It's not actually a file handle that has lock semantics on the underlying resource. You can even create File instances to non-existent resources.

Comments

0

Yes. Having a File instance has little to do with the actual file system until you call one of its methods. In fact, you can create File instances of paths that don't even exist.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.