Win a copy of Event Streams in Action this week in the Java in General forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

How to check if I'm reading the same file

Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Say I open a file, do some stuff w/ it, and exit the application and the file is closed. After couple of days, I want to read the same file(same path) but not sure if that file is newly created or is the same old file, can anyone tell me how do I check that in JAVA?
Author & Gold Digger
Posts: 7616
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you try to read a file that does not exist you get a FileNotFoundException.
So let's make up a scenario.
Day 1:
you have some stuff to write on disk, so you have to create a FileOutputStream or a FileWriter. Say, we use FileOutputStream. Let's create one:
FileOutputStream outToBackup = new FileOutputStream("c:\temp\backup.bak");
then you write your stuff (outToBackup.write(...); )
Eventually, you close your application.
DAY 12:
You want to read what you stored in your backup file 12 days ago. You create a FileInputStream (or a FileReader) like this:
FileInputStream inFromBackup = new FileInputStream("c:\temp\backup.bak");
Then you read what you need (; )
And finally you close you application.
Note that you can pass a boolean to the FileOutputStream constructor in order to open write to the file in append mode (everything gets written at the end fo the file) or not (everything is written from the beginning of the file, contents may be erased).
That's all there is to file reading and writing...
To sum up, if you create a file and you don't move it, then it's gonna be at the same place even years later.
[ February 21, 2002: Message edited by: Valentin Crettaz ]
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm still not entirely sure what the original question was, but you may also want to make sure of some File methods like exists() or lastModified(), if there's some question about whether a file is still where you left it, or if some other process has altered it since then.
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!