Java File Operations
1. Create a new File through createNewFile () in the File class.
/**
* Test File Creation
* @ Throws IOException
*/
@ Test
Public void testCreateFile () throws IOException {
File file = new File ("E:/desc.txt ");
If (! File. exists ()){
File. createNewFile ();
}
}
2. Create a folder
Public void testCreatePath (){
File file = new File ("E:/abcd ");
If (! File. exists ()){
System. out. println ("directory does not exist, automatic creation ");
File. mkdirs ();
}
}
Note: When the mkdirs () method is used, mkdir () or mkdirs () can be used only for the first-level path. When there is a multi-level path (E: \ abc \ test ), only mkdirs () methods can be used.
3. Read an object
Public void testReadFile () throws IOException {
File file = new File ("E:/desc.txt ");
If (! File. exists () | file. isDirectory ()){
Throw new FileNotFoundException ();
}
BufferedReader bf = new BufferedReader (new FileReader (file ));
String line = null;
StringBuffer sb = new StringBuffer ();
While (line = bf. readLine ())! = Null ){
Sb. append (line + "");
Line = bf. readLine ();
}
System. out. println (sb );
}
4. Write content into the file
Public void testBufferedWrite (){
Try {
BufferedWriter bfw = new BufferedWriter (new FileWriter ("E: \ demo.txt "));
Bfw. write ("this is my java! ");
Bfw. flush ();
Bfw. close ();
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
5. Copy files
Public void testCopyFile () throws IOException {
// Create an input stream object
FileInputStream in = new FileInputStream ("E:/test.txt ");
File file = new File ("E:/desc.txt"); // determines whether the File exists.
If (! File. exists ()){
System. out. println ("file does not exist ");
File. createNewFile ();
}
FileOutputStream out = new FileOutputStream (file );
Int c;
Byte buffer [] = new byte [1024];
While (c = in. read (buffer ))! =-1 ){
For (int I = 0; I <c; I ++ ){
Out. write (buffer [I]);
}
}
In. close ();
Out. close ();
}