The most basic file and directory manipulation methods in Java programming

  • 2020-04-01 04:23:35
  • OfStack

File operations

Usually often use JAVA to file operations such as read and write, here is a summary of common file operations.

1. Create a file


public static boolean createFile(String filePath){ 
  boolean result = false; 
  File file = new File(filePath); 
  if(!file.exists()){ 
    try { 
      result = file.createNewFile(); 
    } catch (IOException e) { 
      e.printStackTrace(); 
    } 
  } 
   
  return result; 
} 

2. Create folders


public static boolean createDirectory(String directory){ 
  boolean result = false; 
  File file = new File(directory); 
  if(!file.exists()){ 
    result = file.mkdirs(); 
  } 
   
  return result; 
} 

Delete files


public static boolean deleteFile(String filePath){ 
  boolean result = false; 
  File file = new File(filePath); 
  if(file.exists() && file.isFile()){ 
    result = file.delete(); 
  } 
   
  return result; 
} 

4. Delete folders

Recursively deletes subfiles and folders under folders


public static void deleteDirectory(String filePath){ 
  File file = new File(filePath); 
  if(!file.exists()){ 
    return; 
  } 
   
  if(file.isFile()){ 
    file.delete(); 
  }else if(file.isDirectory()){ 
    File[] files = file.listFiles(); 
    for (File myfile : files) { 
      deleteDirectory(filePath + "/" + myfile.getName()); 
    } 
     
    file.delete(); 
  } 
} 

Read the document

(1) read files in bytes, usually used to read binary files, such as pictures, sounds, images, etc


public static String readFileByBytes(String filePath){ 
  File file = new File(filePath); 
  if(!file.exists() || !file.isFile()){ 
    return null; 
  } 
   
  StringBuffer content = new StringBuffer(); 
   
  try { 
    byte[] temp = new byte[1024]; 
    FileInputStream fileInputStream = new FileInputStream(file); 
    while(fileInputStream.read(temp) != -1){ 
      content.append(new String(temp)); 
      temp = new byte[1024]; 
    } 
     
    fileInputStream.close(); 
  } catch (FileNotFoundException e) { 
    e.printStackTrace(); 
  } catch (IOException e) { 
    e.printStackTrace(); 
  } 
   
  return content.toString(); 
} 

  (2) to read the file as a unit of characters, often used to read text, Numbers and other types of files, support to read Chinese


public static String readFileByChars(String filePath){ 
  File file = new File(filePath); 
  if(!file.exists() || !file.isFile()){ 
    return null; 
  } 
   
  StringBuffer content = new StringBuffer(); 
  try { 
    char[] temp = new char[1024]; 
    FileInputStream fileInputStream = new FileInputStream(file); 
    InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "GBK"); 
    while(inputStreamReader.read(temp) != -1){ 
      content.append(new String(temp)); 
      temp = new char[1024]; 
    } 
     
    fileInputStream.close(); 
    inputStreamReader.close(); 
  } catch (FileNotFoundException e) { 
    e.printStackTrace(); 
  } catch (IOException e) { 
    e.printStackTrace(); 
  } 
   
  return content.toString(); 
} 

(3) read a file in a behavior unit, often used to read a line-oriented format file


public static List<String> readFileByLines(String filePath){ 
  File file = new File(filePath); 
  if(!file.exists() || !file.isFile()){ 
    return null; 
  } 
   
  List<String> content = new ArrayList<String>(); 
  try { 
    FileInputStream fileInputStream = new FileInputStream(file); 
    InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "GBK"); 
    BufferedReader reader = new BufferedReader(inputStreamReader); 
    String lineContent = ""; 
    while ((lineContent = reader.readLine()) != null) { 
      content.add(lineContent); 
      System.out.println(lineContent); 
    } 
     
    fileInputStream.close(); 
    inputStreamReader.close(); 
    reader.close(); 
  } catch (FileNotFoundException e) { 
    e.printStackTrace(); 
  } catch (IOException e) { 
    e.printStackTrace(); 
  } 
   
  return content; 
} 

6. Write documents

Of the classes where strings are written to files, FileWriter is the most efficient, BufferedOutputStream is the next most efficient, and FileOutputStream is the worst.

(1) write to the file through the FileOutputStream


public static void writeFileByFileOutputStream(String filePath, String content) throws IOException{ 
  File file = new File(filePath); 
  synchronized (file) { 
    FileOutputStream fos = new FileOutputStream(filePath); 
    fos.write(content.getBytes("GBK")); 
    fos.close(); 
  } 
} 

(2) write to the file through a BufferedOutputStream


public static void writeFileByBufferedOutputStream(String filePath, String content) throws IOException{ 
  File file = new File(filePath); 
  synchronized (file) { 
    BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(filePath)); 
    fos.write(content.getBytes("GBK")); 
    fos.flush(); 
    fos.close(); 
  } 
} 

(3) write a string to a file through a FileWriter


public static void writeFileByFileWriter(String filePath, String content) throws IOException{ 
    File file = new File(filePath); 
    synchronized (file) { 
      FileWriter fw = new FileWriter(filePath); 
      fw.write(content); 
      fw.close(); 
    } 
  } 

Directory operations
A directory is a list of files that can contain other files and directories. If you want to make a list of available files in a directory, you can create a directory using the File object to get a full and detailed list of methods that can be invoked in the File object and about the directory.

Create a directory
Here are two useful file methods for creating directories:

The mkdir() method creates a directory that returns true on success and false on failure. A failure is when the path to the file object already exists, or the directory cannot be created because the entire path does not exist.
The mkdirs() method creates a directory and its parent directory.
The following example creates the directory "/ TMP/user/Java/bin" :


import java.io.File;

public class CreateDir {
  public static void main(String args[]) {
   String dirname = "/tmp/user/java/bin";
   File d = new File(dirname);
   // Create directory now.
   d.mkdirs();
 }
}

Compile and execute the above code to create "/ TMP /user/ Java/bin".

Tip: Java automatically handles path separators according to UNIX and Windows conventions. If you use a forward slash (/) in the Windows version of Java, you can still get the correct path.

Directory listing
Below, you can use the list() method provided by the File object to list all available files and directories in the directory


import java.io.File;

public class ReadDir {
  public static void main(String[] args) {

   File file = null;
   String[] paths;

   try{   
     // create new file object
     file = new File("/tmp");

     // array of files and directory
     paths = file.list();

     // for each name in the path array
     for(String path:paths)
     {
      // prints filename and directory name
      System.out.println(path);
     }
   }catch(Exception e){
     // if any error occurs
     e.printStackTrace();
   }
  }
}

Based on the directories and files available in your/TMP directory, the following results will be produced:


test1.txt
test2.txt
ReadDir.java
ReadDir.class


Related articles: