• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

File operations in java

September 29, 2011 By j2eereference Leave a Comment

Files in Java

java provides java.io.File class for handling file / directories  operations .

Creating a File object :

File file = new File(“file1.txt”);

A File object represents name and path of a file or directory on a Disk. In the above code just File

object has been created actual file is not yet created in the current directory. If you don’t know the

current directory you can get it this way:

String userdir = System.getProperty(“user.dir”);   //returns user current directory.

 Check the existance of File or Directory

1) boolean exists() – Checks whether file exist or not

2) boolean isFile() – Checks it is a file or not.

3) boolean isDirectory() – Checks it is a directory or not.

4) String[] list() – return the names of all files and directories in a directory

5) String getName() – returns file or directory’s name

6) String getPath() – returns file or directory’s path.

 

Below are the examples given to create file/directories, deleting file/directories, renaming and copying files.

 

Creating a Directory:

You can create a Directory using the method mkdir() , lets create a directory mydir using the below code

1
2
3
4
5
6
7
8
<strong>import </strong>java.io.File;
<strong></strong><strong>public</strong> <strong>class</strong>Test {<strong>
public</strong> <strong>static</strong> <strong>void</strong> main(String[] args)
{
File myDir = <strong>new</strong> File("mydir");
myDir.mkdir();
}
}

 

Creating a file:

In java, file is created using createNewFile() method. Below is the example to create a file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<strong>import </strong>java.io.File;<strong>
public</strong> <strong>class </strong>FileDemo {<strong>
public</strong> <strong>static</strong> <strong>void </strong>main(String[] args) {
<strong>try</strong>
{
File file = <strong>new</strong> File("file1.txt");
System.<em>out</em>.println(file.exists());
file.createNewFile();
System.<em>out</em>.println(file.exists());
}
<strong>catch</strong>(IOException ex){
ex.printStackTrace();
}
}
}

Output :

false

true

Creating a Directory:

We can create a directory using mkdir() method. Creating a directory and file is shown below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<strong>import </strong>java.io.*;
<strong>public</strong> <strong>class </strong>FileDemo {
<strong>public</strong> <strong>static</strong> <strong>void</strong> main(String[] args) {
<strong>try</strong>
{
File myDir = <strong>new</strong> File("mydir");
myDir.mkdir();    //creates directory
File file = <strong>new</strong> File(myDir, "myfile.txt");
file.createNewFile();
}
<strong>catch</strong>(IOException ex){
ex.printStackTrace();
}
}
}

Output: File “myfile.txt” will be created under mydir.

Renaming a File:

Current directory contains the file named “file1”, we will rename it to “file2”.

1
2
3
4
5
6
7
8
9
<strong>import </strong>java.io.*;
<strong>public</strong> <strong>class </strong>FileDemo {
<strong>public</strong> <strong>static</strong> <strong>void</strong>main(String[] args) {
File file = <strong>new</strong>File("file1.txt");
<strong>if</strong>(file.exists());{
file.renameTo(<strong>new</strong> File("file2.txt") );
}
}
}

Output: file name file1 will be renamed to file2 in current directory.

Deleting a File:

1
2
3
4
5
6
7
8
9
<strong>import </strong>java.io.*;
<strong>public</strong> <strong>class </strong>FileDemo {
<strong>public</strong> <strong>static</strong> <strong>void</strong> main(String[] args) {
File file = <strong>new</strong> File("file1.txt");
<strong>if</strong>(file.exists());{
file.delete();
}
}
}

Output: File “file1.txt” deleted from current directory.

Deleting a file from a specific directory

1
2
3
4
5
6
7
8
9
10
11
<strong>import </strong>java.io.*;
<strong></strong><strong>public</strong> <strong>class </strong>FileDemo {<strong>
public</strong> <strong>static</strong> <strong>void</strong> main(String[] args) {
File myDir = <strong>new</strong> File("mydir");
myDir.mkdir();
File file = <strong>new</strong> File(myDir , "file1.txt");
<strong>if</strong>(file.exists());{
file.delete();
}
}
}

Output : “file1.txt” get deleted from the mydir.

Note : you cannot delete a directory if it is not  empty.

Deleting all the files in a Deirectory:

Below code will show you how to delete all the files in a Directory

1
2
3
4
5
6
7
8
9
10
11
<strong>import </strong>java.io.File;
<strong></strong><strong>public</strong> <strong>class</strong>Test{<strong></strong>
<strong>public</strong> <strong>static</strong> <strong>void</strong>main(String[] args)
{
File myDir = <strong>new</strong> File("mydir");
File[] files = myDir.listFiles();
<strong>for</strong>(<strong>int</strong> i=0; i&lt;files.length; i++) {
files[i].delete();
}
}
}

Copying Files:

In java files can be copied using copyfile method which copies content of one file to another file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<strong>import </strong>java.io.*;
<strong>public</strong> <strong>class </strong>CopyFileDemo{<strong>
public void</strong>copyfile(String src, String dst){
<strong>try </strong>
{
File file1 = new File(src);
File file2 = new File(dst);
InputStream in = <strong>new</strong> FileInputStream(file1);
OutputStream out = <strong>new</strong> FileOutputStream(file2);
byte[] buf = <strong>new </strong>byte[4096];
int len;
while ((len = in.read(buf)) &gt; 0)
{
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
}
catch(FileNotFoundException ex){
ex.printStackTrace();
}
catch(IOException ex){
ex.printStackTrace();
}
}
<strong>public static void</strong> main (String args[])
{
CopyFileDemo cp = <strong>new</strong> CopyFileDemo();
cp.copyfile("file1.txt","file2.txt");
}
}

Related Posts

  • Busy Spinning in mutithreading
  • Implementing queue in java
  • TreeSet vs ConcurrentSkipListSet
  • How to create immutable class?
  • Implementing Stack in java
  • What is ReentrantLock?
  • What is Semaphore in java
  • Why AtomicInteger class
  • What is CyclicBarrier?
  • CountDownLatch in java

Filed Under: Core Java

Reader Interactions

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • What is parallel Stream
  • reduce method of the Stream class
  • Difference between the findFirst() and findAny() method
  • intern() method of String class
  • SOLID – Five principles of object-oriented software design
  • Java Coding Best Practices
  • How to use lambda expression effectively
  • Enhanced pseudo-Random Number Generators in java17
  • How to use Foreign-Memory Access API
  • Pattern Matching for instanceof
  • Text Blocks – Feature added in Java17
  • Record – The new feature added in java 17
  • What is Sealed Class
  • Features added in Java 17
  • Java Buzzwords

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.