File Operation
JAVA is often used to read and write files, so here is a summary of commonly used 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.createNewF ile(); } catch (IOException e) { e.printStackTrace(); } } return result; }2. Create a folder
public static boolean createDirectory(String directory){ boolean result = false; File file = new File(directory); if(!file.exists()){ result = file.mkdirs (); } return result; }3. Delete the file
public static boolean deleteFile(String filePath){ boolean result = false; File file = new File(filePath); if(file.exists() && file.isFile()){ result = fi le.delete(); } return result; }4. Delete the folder
Recursively delete sub-files 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(); } }5. Read the file
(1) Read files in bytes, which are often used to read binary files, such as pictures, sounds, images and other files
public static String readFileByBytes(String filePath){ File file = new File(filePath); if(!file.exists() || !file.isFile()){ return null; } StringBuff er content = new StringBuffer(); try { byte[] temp = new byte[1024]; FileInputStream fileInputStream = new FileInputStream(file); while(fileInputStream.read(temp) != -1){ content.append(new Strin g(temp)); temp = new byte[ 1024]; } fileInputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } retu rn content.toString(); }(2) Read files in units of characters, which are often used to read files of text, numbers, etc., and support reading 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(fileInputStrea m, "GBK"); while(inputStreamReader.read(temp) != -1){ content.append (new String(temp)); temp = new char[1024]; } fileInputStream.close(); inputStreamReader.close(); } catch (FileNotFoundException e) { e.printStackT race(); } catch (IOException e) { e .printStackTrace(); } return content.toString(); }(3) Read files in behavior units, often used to read line-oriented formatted files
public static List<String> readFileByLines(String filePath){ File file = new File(filePath); if(!file.exists() || !file.isFile()){ return null; } List<S Tring> content = new ArrayList<String>(); try { FileInputStream fileInputStream = new FileInputStream(file); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStrea m, "GBK"); BufferedReader reader = new BufferedReader(inputStreamReader); String lineContent = ""; while ((lineContent = reader.readLine()) != null) { content.add(lineContent); System.out.println(lineContent); } fileInputStream.close(); inputStreamReader.close(); re ader.close(); } catch ( FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return content; }6. Write a document
Among the several classes in which strings are written to files, FileWriter is the most efficient, followed by BufferedOutputStream, and FileOutputStream is the worst.
(1) Write files through FileOutputStream
public static void writeFileByFileOutputStream(String filePath, String content) throws IOException{ File file = new File(filePath); synchronized (file) { Fi leOutputStream fos = new FileOutputStream(filePath); fos.write(content.getBytes("GBK")) ; fos.close(); } }(2) Write files through 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 strings to file through FileWriter
public static void writeFileByFileWriter(String filePath, String content) throws IOException{ File file = new File(filePath); synchronized (file) { FileWrit er fw = new FileWriter(filePath); fw.write(content); fw.close(); } } Directory Operation
A directory is a list of files that can contain other files and directories. If you want to list the list of available files in a directory, you can create a directory using the File object to obtain a complete and detailed list of methods that can be called in the File object and related to the directory.
Create a directory
Here are two useful file methods that can create directories:
The mkdir( ) method creates a directory, returns true for success, and returns false for failure to create. A failure situation means that 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 upper directory.
The following example creates the "/tmp/user/java/bin" directory:
import java.io.File;public class CreateDir { public static void main(String args[]) { String dirname = "/tmp/user/java/bin"; File d = new File(dirna me); // 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 forward slash (/) in Windows versions of Java, you can still get the correct path.
Directory list
As follows, 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.txttest2.txtReadDir.javaReadDir.class