Author Topic: How to work with File in Java  (Read 90 times)

Iman

  • Administrator
  • Newbie
  • *****
  • Posts: 13
    • View Profile
How to work with File in Java
« on: August 21, 2018, 08:33:44 PM »
Hi Folks,

Let's dive a little bit more into the concept of file stream, different processes in your machine can talk to each other using file stream and if that process is located in another machine and connected to this machine usually using the internet is called socket. There is a broad area about socket programming and that I am not going to cover that in this class, but file stream is something you need to know as I have maintained that in homework #2.

You can read/write from/to a file using java.IO.File package, but you need first to make sure that file is available and there is an option that is going to show if the file is not available; then, will make a new file.

I will cover a few use cases below, but for all use cases we have to make that connection stream to that file which is:

 File aFile = new File("C:\\User\\Iman\\file.txt");

Use case #1: we want to see does the file exist or not:

aFile.exists() ;// this will return a boolean value (true/false) to see does the file exist or not.

Use case #2: create a new file.

aFile.createNewFile(); // this will return a boolean value (true/false), if it returns a false value, it should be an error which might explain why it couldn't make that file.

Use case #2: do you have permission to read from a file?

aFIle.canRead(); // Tests whether the application can read the file denoted    by this abstract pathname.

Use case #3: do you have permission to write into a  file?

aFile.canWrite(); // Tests whether the application can modify the file denoted by this abstract pathname.

These are some use cases that you might need to complete your homework #2.

Regards,
Iman