Package Com.starain.io;
Import Java.io.BufferedWriter;
Import Java.io.File;
Import Java.io.FileWriter;
Import java.io.IOException;
public class FileOperation {
public static void Main (string[] args) throws IOException {
File File1 = new file ("D:\\hello4.txt");
File File2 = new file ("D:\\hello4.txt");
if (file1.exists ()) {//Determine if File1 file exists
File1.delete ();//delete file1 file
}
/* Test if FILE1 has been deleted */
if (file1.exists ()) {
System.out.println ("file existed");
}else {
System.out.println ("had been deleted");
}
/* Create File2 If File2 does not exist, and then name test5.txt*/
if (!file2.exists ()) {
Throw exception
try {
File2.createnewfile ();//Create File
SYSTEM.OUT.PRINTLN ("file has been created");
} catch (IOException e) {
SYSTEM.OUT.PRINTLN ("File cannot be created");
}
if (File2.isfile ()) {
Renaming
File name = new file ("D:\\test5.txt");
File2.renameto (name);
}
/* Write file */
FileWriter form, without buffering, suitable for less content
String pathName1 = "D:/test5.txt";
FileWriter filewriter1 = new FileWriter (pathName1);//May throw an exception, so use throw IOException or try{}catch{}
Filewriter1.write ("This is a Test program\n");
Filewriter1.write ("Hello World");
Filewriter1.close ();//Because the program executes more quickly, but the file reads and writes slowly,
Not calling the close () method may cause the file to be written (not finished), the program executes, the write operation terminates, some data is not written up
BufferedWriter Efficient buffer Flow class
String pathName2 = "d:\\test6.txt";//The file is created automatically when it does not exist, overwriting the old file when it exists
BufferedWriter filewriter2 = new BufferedWriter (new FileWriter (pathName2));
/*string pathName2 = "D:/test6.txt";
* FileWriter file1 = new FileWriter (pathName2);
* BufferedWriter filewriter2 = new BufferedWriter (file1);
*/
Filewriter2.write ("Test6");
Filewriter2.write ("\nhello");//A system that encounters a non-\ line break causes the line to break normally
Filewriter2.newline ();//newline () method can solve the problem of different methods of line-wrapping between different systems.
Filewriter2.write ("World");
Filewriter2.close ();//Close stream
}
}
}
Java file (folder) operations