Java File Handling

We need to use Java File handling class from java.io package.
import java.io.File; 
Using the above file class we will create one object.
File my_file_obj = new File("my_new_file.txt");
Here my_new_file.txt is the name of the file. To handle the exceptions we will include the pacakge IOException.

createNewFile()

We will be using createNewFile() method of File class to create new file. This method returns true or false based on the successful creation of file.

Here is the code to create a new file.
package Pack1;
import java.io.File; 
import java.io.IOException; 
public class my_file {
	public static void main(String[] args) {
	try {
	    File my_file_obj = new File("my_new_file.txt"); // file object
	      if (my_file_obj.createNewFile()) {
	        System.out.println("New File created: ");
	      } else {
	        System.out.println("File already exists.");
	      }
	    
    } catch (IOException e) {
    System.out.println("OOps some error.");
    e.printStackTrace();
  }
}
}
We used my_file_obj as file object and createNewFile() method to create new file. In above code we have included try.. catch to get the exceptions in our file creating process.

Location of the new file.

In above code the file is created in the current or project directory. This depends on setting and project you are using in your system. Here is one sample path of default file creation
C:>users>user_name>eclipse-workplaces>java_projects
We can create our own path to store the files.
Let us modify the code above to store files in D drive .
File my_file_obj = new File("D:\\java_files\\my_new_file.txt");
This code will create the file in a directory java_files of my D drive.

For Mac or Linux the path can be
/Users/java_files/my_new_file.txt

file.separator

We can get how the file system separator work in the system and use it to make our script universal.


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer