Posted in Uncategorized

[Java Core] File handling in Java

java_logo_100

In Java, we often handle a file. Now, I want to introduce some code for handling file basically.

  • Create a folder
public void createFolder(String newFolderPath) {
    new File(newFolderPath).mkdir();
}
  • Create a folder and its subfolder
/**
* @param path such as "C:\\Directory2\\Sub2\\Sub-Sub2"
*/
public void createFolderAndItsSubFolders(String path) {
   new File(path).mkdirs();
}
  • Check a folder existed or not
/**
* @param path such as "C:\\Directory1"
*/
public boolean isExistedFolder(String folder) {
   File file = new File(folder);
   return file.exists();
}
  • Create new file
public void createNewFile(String filePath) {
    try {
      File file = new File(filePath);
      if (file.createNewFile()) {
        System.out.println("File is created!");
      } else {
        System.out.println("File already exists.");
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
 }
  • Delete a file
public void deleteFile(String filePath) {
    try {
      File file = new File(filePath);
      if (file.delete()) {
        System.out.println(file.getName() + " is deleted!");
      } else {
        System.out.println("Delete operation is failed.");
      }
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("IOException: " + e.getMessage());
    }
  }
  • Open a file by default app in PC such as open HTML file on Chrome
public void openFileOnDefaultApp(String filePath) {
    File htmlFile = new File(filePath);
    try {
      Desktop.getDesktop().browse(htmlFile.toURI());
    } catch (IOException e) {
      e.printStackTrace();
      System.out.println("IOException: " + e.getMessage());
    }
 }

 

You also can find above source at this class file

Like and share this topic if it is helpful for you 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s