• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

File I/O R/W + Permission Issue

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here i have this program

i am running on a Windows 7 PC installed on my C: Drive and an external HDD as my E: Drive
this is just a test for reading and writing simple text files to the hard disk..
The program compiles well.. (it was compiled on JDk7u1)
If the filepath is "C:/Test.txt", there is nothing as output..
And the following is printed as Trace:

java.io.IOException: Access is denied
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:947)
at TestFileOverWritePermission.main(TestFileOverWritePermission.java:9)
at __SHELL32.run(__SHELL32.java:6)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at bluej.runtime.ExecServer$3.run(ExecServer.java:724)

which simply means i got an IOException.. So i suspect bluej isnt getting the permission to write to my C:/ Drive.. So i fired bluej using "Run As Administrator".. Now i cud write to the file..
but the program isnt able to print the text i wanted it to store.. in the output terminal..

To use the program in normal mode, i edited the file location to "E:/Test.txt".
Now obviously noI/O Exceptions occurred..
By navigating to the location, i could find the file.. and It displays clearly my string "Testtext" in notepad.. but my program cant read it..
I tried commenting as many lines possible but still there's no way out..
its s simple silly mistake i guess (but dats too hidden for me to detect) :p
here is the output

[Output]
TestFileOverWritePermission.main({ });
OverWrite? --> false
-1
-1
null
[/Output]

If the file already existed.. the boolean value printed is true..
But in neither case m i able to see "Testtext"

Please help.. the error is logical and may arise out of multiple function calls..
One more question- Is the sequence of the .close() anyway important.. is it even essential to use it der.. If the .close() call is not made.. i can see no output..

Thanks in Advance!
 
Sheriff
Posts: 22802
131
Eclipse IDE Spring Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

MikeJava iNtelMac wrote:


That comment is a lie. It moves the file's read position one ahead if there's data in it. Likewise for the brt.read() call.


That's because the data hasn't been written to disk yet. You need to at least flush() the writer, preferably close() it already. Those will cause the data to be actually written to the file.

Now i cud write to the file..


Please UseRealWords: "could", not "cud".
 
Miling Shah
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Rob!
Here is my interpretation of your reply..
Until i flush the writer or close the FileWriter object, the data is not written to the exact location of the File object and stays in the Java heap space.. The .close() call fixes everything now..

But the file permission issue still persists..
But as i execute the program for the path "C:/Test.txt" with an already-existing Test.txt file there.. Running in non-admin mode..
I get this output:
[Output]
OverWrite? --> true
[/Output]

and the following as Stack Trace

java.io.FileNotFoundException: C:\Test.txt (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
at java.io.FileOutputStream.<init>(FileOutputStream.java:165)
at java.io.FileWriter.<init>(FileWriter.java:90)
at TestFileOverWritePermission.main(TestFileOverWritePermission.java:10)
at __SHELL3.run(__SHELL3.java:6)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at bluej.runtime.ExecServer$3.run(ExecServer.java:724)

If FileNotFoundException is thrown, then how come File overwrite check could be printed as true?

For the path "E:Test.txt"
i changed the code to call fw.close() before the read operation!

Here is the snippet


following is the output:
[Output]
OverWrite? --> true
fr1.read() --> 101
brt.read() --> 116
brt.readLine() --> Text
[/Output]

So i was wondering why only "Text" in place of TestText" whereas the file properly shows "TestText" when opened in notepad..

What i believe is when i am reading the file again via this code:



i understood why 101 & 116 are printed and then "Text" but cant figure out then why the characters 'T' & 's' were skipped..

Try and Help me.. in case i am going wrong anywhere..

Thanks Rob, I will make sure i type RealWords now onwards!
 
Rob Spoor
Sheriff
Posts: 22802
131
Eclipse IDE Spring Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

MikeJava iNtelMac wrote:If FileNotFoundException is thrown, then how come File overwrite check could be printed as true?


The exception name is not correct in this case. The file can be found, it just can't be written to. Windows is blocking your request. My guess is that you're running Windows Vista or Windows 7, where certain paths (C:, C:\Program Files and its sub folders, C:\Windows and its sub folders) have additional protection. Some programs let Windows show a dialog to ask for permission, others (including the JVM) do not and Windows simply disallows it.

So i was wondering why only "Text" in place of TestText" whereas the file properly shows "TestText" when opened in notepad..

What i believe is when i am reading the file again via this code:


Correct.

i understood why 101 & 116 are printed and then "Text" but cant figure out then why the characters 'T' & 's' were skipped..


They are read, you just don't do anything with the values. The code on lines 2 and 5 of your code each reads a character and move the file position forward. As a result the two characters are read but ignored.
One more word of caution. Once you create your BufferedReader, that may read characters in advance. If you would read from fr1 between lines 5 and 6 you may not get the 't' because the BufferedReader may have already read it and stored it in its cache. Reading directly from the FileReader will then continue where the BufferedReader left off.
 
Miling Shah
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for the clarification..
You were absolutely right, i am running (via BlueJ) on Windows 7!

Well now as i you said.. i believe FileReader, BufferedReader and similar classes have synchronized methods that maintain a certain virtual or hidden lock on the file object being accessed.. isnt it?

If yes,do i need to call the .close() method on a FileReader object (being used first as compared to the BufferedReader object) and then read from the BufferedReader.. or is it Okay without .close() calls..

Why doesn't the File class have a .close() method.. so that whenever any other object, say a FileReader/Writer or FileInput/OutputStream object has finished its job.. the self-lock is activated.. something like a data protection feature.. ? Or any idea how i can implement it.?

i am retyping my old question in case you can help-

Does the sequence of function call for object of classses operating on File objects such as FileReader, FileWriter, BufferedReader, BufferedWriter etc.. matter.. any rules as such to be followed?
 
Rob Spoor
Sheriff
Posts: 22802
131
Eclipse IDE Spring Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Miling Shah wrote:Well now as i you said.. i believe FileReader, BufferedReader and similar classes have synchronized methods that maintain a certain virtual or hidden lock on the file object being accessed.. isnt it?


Java doesn't automatically lock files. Windows usually puts a lock on the file, but that only prevents you from deleting / moving it, not from reading / writing it from another program (or even another thread in the same program).

If yes,do i need to call the .close() method on a FileReader object (being used first as compared to the BufferedReader object) and then read from the BufferedReader.. or is it Okay without .close() calls..


If you close() the FileReader you can't read anything from it anymore, also not using the BufferedReader. Once you've created the BufferedReader you should simply never read from the FileReader anymore, just from the BufferedReader. The latter is a wrapper around the FileReader (or any other reader it's created with), and it delegates reading to that FileReader. It just reads a bit more sometimes and caches that.

Why doesn't the File class have a .close() method..


Because a File does not represent a physical file. It's more like a file name through which you can also query the file's properties (but not its contents).

so that whenever any other object, say a FileReader/Writer or FileInput/OutputStream object has finished its job.. the self-lock is activated.. something like a data protection feature.. ? Or any idea how i can implement it.?


You should simply close all readers, writers and streams once you're done with them. The new try-with-resources syntax will help you with that.

Does the sequence of function call for object of classses operating on File objects such as FileReader, FileWriter, BufferedReader, BufferedWriter etc.. matter.. any rules as such to be followed?


The sequence indeed matters. A few examples:
- You can't read from or write to a reader / writer / stream after it has been closed.
- You can't guarantee that data is actually written until you flush() or close() the writer / stream.
- You must create a mark before you can reset to that mark.
 
Miling Shah
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot Rob!

I tried closing Reader objects at different places in the code (and even reclosed them to check what happens) and understood all that you had just explained very clearly..
It was like i was just confirming what i had just learnt!

Closing a superclass object closes all subclass objects - like closing FileReader object stream also closes the BufferedReader object stream..

I assume that's what you meant by


The new try-with-resources syntax will help you with that.



Merry Christmas!
 
Rob Spoor
Sheriff
Posts: 22802
131
Eclipse IDE Spring Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Miling Shah wrote:Closing a superclass object closes all subclass objects - like closing FileReader object stream also closes the BufferedReader object stream..


They're not super / sub classes, they are wrapping and wrapped objects. Closing a FileReader object closes the wrapping BufferedReader, but perhaps not immediately. There may still be cached data. Closing a BufferedReader will close the wrapped FileReader (or any other Reader) directly.

I assume that's what you meant by


The new try-with-resources syntax will help you with that.


I actually meant that the new syntax will automatically close anything you declare inside the try-with-resources header. For instance:
The old syntax made it easier to forget to close resources like FileReaders.

Merry Christmas!


And too you too!
 
You've gotta fight it! Don't give in! Read this tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic