Home>

File operations

I usually use java to read and write files.Here is a summary of common file operations.

1.Create 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;
}

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;
}

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 the folder

Recursively delete subfiles and folders below a folder

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 files

(1) read the file in bytes,Commonly used to read binary files,Files such as pictures, sounds, videos, 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) read the file in characters,Often used to read text,Digital and other types of files,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 the file in units of behavior,Commonly 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<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;
}

Write files

Strings are written into several classes of the file,filewriter is most efficient,BufferedOutputStream is next, and FileOutputStream is the worst.

(1) Write to file through 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 file 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 string to file through 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 operationsA directory is a list of files that can contain other files and directories.You want to list the available files in the directory,You can create directories by using the file object,Get a complete and detailed list of methods that can be called in a file object and related directories.

Create a directoryHere are two useful file methods.Ability to create directories:

The mkdir () method creates a directory,Returns true on success and false on creation failure. Failure means that the path of the file object already exists,Or unable to create directory,Because the entire path does not exist.

The mkdirs () method creates a directory and its parent directories.

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 (dirname);
   //create directory now.
   d.mkdirs ();
 }
}

Compile and execute the above code to create "/tmp/user/java/bin".

Hint:java automatically handles path separators according to the unix and windows conventions.If you use forward slashes (/) in the windows version of java, you still get the correct path.

Directory listingAs 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 under your/tmp directory,Will produce the following results:

test1.txt
test2.txt
readdir.java
readdir.class
  • Previous js pop up dialog box summary
  • Next Learn me about floating point precision in javascript