Java File Operations

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.