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 🙂