This page discusses the details of reading, writing, creating, and opening files. There are a wide array of file I/O methods to choose from. To help make sense of the API, the following diagram arranges the file I/O methods by complexity.
On the far left of the diagram are the utility methods
readAllBytes
, readAllLines
, and the write
methods, designed for simple, common cases. To the right of those are the methods used to iterate over a stream or lines of text, such as newBufferedReader
, newBufferedWriter
, then newInputStream
and newOutputStream
. These methods are interoperable with the java.io
package. To the right of those are the methods for dealing with ByteChannels
, SeekableByteChannels
, and ByteBuffers
, such as the newByteChannel
method. Finally, on the far right are the methods that use FileChannel
for advanced applications needing file locking or memory-mapped I/O.Note: The methods for creating a new file enable you to specify an optional set of initial attributes for the file. For example, on a file system that supports the POSIX set of standards (such as UNIX), you can specify a file owner, group owner, or file permissions at the time the file is created. The Managing Metadata page explains file attributes, and how to access and set them.
This page has the following topics:
The OpenOptions
Parameter
Several of the methods in this section take an optional
OpenOptions
parameter. This parameter is optional and the API tells you what the default behavior is for the method when none is specified.The following
StandardOpenOptions
enums are supported:Java Write To File Line By Line
WRITE
– Opens the file for write access.APPEND
– Appends the new data to the end of the file. This option is used with theWRITE
orCREATE
options.TRUNCATE_EXISTING
– Truncates the file to zero bytes. This option is used with theWRITE
option.CREATE_NEW
– Creates a new file and throws an exception if the file already exists.CREATE
– Opens the file if it exists or creates a new file if it does not.DELETE_ON_CLOSE
– Deletes the file when the stream is closed. This option is useful for temporary files.SPARSE
– Hints that a newly created file will be sparse. This advanced option is honored on some file systems, such as NTFS, where large files with data 'gaps' can be stored in a more efficient manner where those empty gaps do not consume disk space.SYNC
– Keeps the file (both content and metadata) synchronized with the underlying storage device.DSYNC
– Keeps the file content synchronized with the underlying storage device.
Commonly Used Methods for Small Files
Reading All Bytes or Lines from a File
If you have a small-ish file and you would like to read its entire contents in one pass, you can use the
readAllBytes(Path)
or readAllLines(Path, Charset)
method. These methods take care of most of the work for you, such as opening and closing the stream, but are not intended for handling large files. The following code shows how to use the readAllBytes
method:Writing All Bytes or Lines to a File
You can use one of the write methods to write bytes, or lines, to a file.
The following code snippet shows how to use a
write
method.Buffered I/O Methods for Text Files
The
java.nio.file
package supports channel I/O, which moves data in buffers, bypassing some of the layers that can bottleneck stream I/O.Reading a File by Using Buffered Stream I/O
The
newBufferedReader(Path, Charset)
method opens a file for reading, returning a BufferedReader
that can be used to read text from a file in an efficient manner.The following code snippet shows how to use the
newBufferedReader
method to read from a file. The file is encoded in 'US-ASCII.'Writing a File by Using Buffered Stream I/O
You can use the
newBufferedWriter(Path, Charset, OpenOption..)
method to write to a file using a BufferedWriter
.The following code snippet shows how to create a file encoded in 'US-ASCII' using this method:
Methods for Unbuffered Streams and Interoperable with java.io
APIs
Reading a File by Using Stream I/O
To open a file for reading, you can use the
newInputStream(Path, OpenOption..)
method. This method returns an unbuffered input stream for reading bytes from the file.Creating and Writing a File by Using Stream I/O
You can create a file, append to a file, or write to a file by using the
newOutputStream(Path, OpenOption..)
method. This method opens or creates a file for writing bytes and returns an unbuffered output stream.The method takes an optional
OpenOption
parameter. If no open options are specified, and the file does not exist, a new file is created. If the file exists, it is truncated. This option is equivalent to invoking the method with the CREATE
and TRUNCATE_EXISTING
options.The following example opens a log file. If the file does not exist, it is created. If the file exists, it is opened for appending.
Methods for Channels and ByteBuffers
Reading and Writing Files by Using Channel I/O
While stream I/O reads a character at a time, channel I/O reads a buffer at a time. The
ByteChannel
interface provides basic read
and write
functionality. A SeekableByteChannel
is a ByteChannel
that has the capability to maintain a position in the channel and to change that position. A SeekableByteChannel
also supports truncating the file associated with the channel and querying the file for its size.The capability to move to different points in the file and then read from or write to that location makes random access of a file possible. See Random Access Files for more information.
There are two methods for reading and writing channel I/O.
Note: The
newByteChannel
methods return an instance of a SeekableByteChannel
. With a default file system, you can cast this seekable byte channel to a FileChannel
providing access to more advanced features such mapping a region of the file directly into memory for faster access, locking a region of the file so other processes cannot access it, or reading and writing bytes from an absolute position without affecting the channel's current position.Both
newByteChannel
methods enable you to specify a list of OpenOption
options. The same open options used by the newOutputStream
methods are supported, in addition to one more option: READ
is required because the SeekableByteChannel
supports both reading and writing.Specifying
READ
opens the channel for reading. Specifying WRITE
or APPEND
opens the channel for writing. If none of these options is specified, the channel is opened for reading.The following code snippet reads a file and prints it to standard output:
The following example, written for UNIX and other POSIX file systems, creates a log file with a specific set of file permissions. This code creates a log file or appends to the log file if it already exists. The log file is created with read/write permissions for owner and read only permissions for group.
Methods for Creating Regular and Temporary Files
Creating Files
You can create an empty file with an initial set of attributes by using the
createFile(Path, FileAttribute<?>)
method. For example, if, at the time of creation, you want a file to have a particular set of file permissions, use the createFile
method to do so. If you do not specify any attributes, the file is created with default attributes. If the file already exists, createFile
throws an exception.In a single atomic operation, the
createFile
method checks for the existence of the file and creates that file with the specified attributes, which makes the process more secure against malicious code.The following code snippet creates a file with default attributes:
POSIX File Permissions has an example that uses
createFile(Path, FileAttribute<?>)
to create a file with pre-set permissions.You can also create a new file by using the
newOutputStream
methods, as described in Creating and Writing a File using Stream I/O. If you open a new output stream and close it immediately, an empty file is created.Creating Temporary Files
You can create a temporary file using one of the following
createTempFile
methods:The first method allows the code to specify a directory for the temporary file and the second method creates a new file in the default temporary-file directory. Both methods allow you to specify a suffix for the filename and the first method allows you to also specify a prefix. The following code snippet gives an example of the second method:
The result of running this file would be something like the following:
The specific format of the temporary file name is platform specific.
1. Overview
In this quick tutorial, we’re going to illustrate how to write an InputStream to a File – first using plain Java, then Guava and finally the Apache Commons IO library.
This article is part of the “Java – Back to Basic” tutorial here on Baeldung.
Java – InputStream to Reader
How to convert an InputStream to a Reader using Java, Guava and the Apache Commons IO library.
Read more →
Java – Convert File to InputStream
How to open an InputStream from a Java File - using plain Java, Guava and the Apache Commons IO library.
Read more →
Java InputStream to Byte Array and ByteBuffer
How to convert an InputStream to a byte[] using plain Java, Guava or Commons IO.
Read more →
2. Convert using plain Java
Let’s start with the Java solution:
Note that in this example, the input stream has known and pre-determined data – such as a file on disk or an in-memory stream. Because of this, we don’t need to do any bounds checking and we can – if memory allows – simply read it and write it in one go.
If the input stream is linked to an ongoing stream of data – for example, an HTTP response coming from an ongoing connection – then reading the entire stream once is not an option. In that case, we need to make sure we keep reading until we reach the end of the stream:
Finally, here’s yet another, simple way we can use Java 8 to do the same operation:
3. Convert using Guava
Next – let’s take a look at a simpler Guava based solution:
4. Convert using Commons IO
Flash zenfone c tidak bisa unzip image failure youtube. And finally – an even quicker solution with Apache Commons IO:
And there you have it – 3 quick ways of writing the InputStream to a File.
I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:
Today we will look into how to append to a file in java. Java append to file is a common java IO operation. For example, whenever we print something to server logs, it gets appended to the existing file.
Table of Contents
- 1 Java append to file
Java append to file
We can append to file in java using following classes.
- Java append to file using
FileWriter
- Java append content to existing file using
BufferedWriter
- Append text to file in java using
PrintWriter
- Append to file in java using
FileOutputStream
If you are working on text data and the number of write operations is less, use FileWriter and use its constructor with append flag value as
true
. If the number of write operations is huge, you should use the BufferedWriter.To append binary or raw stream data to an existing file, you should use FileOutputStream.
Java append to file using FileWriter
Here is the short program to append to file in java using FileWriter. We will look into a complete Java append to file example program later on.
Java append content to existing file using BufferedWriter
Append text to file in java using PrintWriter
We can also use PrintWriter to append to file in java.
Append to file in java using FileOutputStream
You should use FileOutputStream to append data to file when it’s raw data, binary data, images, videos etc.
Java append to file example
Here is the final java append to file program showing all the different options we discussed above.
That’s all for append to file in java program.
You can checkout more Java IO examples from our GitHub Repository.
References:
What's the simplest way to create and write to a (text) file in Java?
Wolf5,52233 gold badges2828 silver badges8080 bronze badges
Drew JohnsonDrew Johnson8,78588 gold badges2828 silver badges3434 bronze badges
30 Answers
Note that each of the code samples below may throw
IOException
. Try/catch/finally blocks have been omitted for brevity. See this tutorial for information about exception handling.Note that each of the code samples below will overwrite the file if it already exists
Creating a text file:
Creating a binary file:
Java 7+ users can use the
Files
class to write to files:Creating a text file:
Creating a binary file:
Matthias3,92655 gold badges4141 silver badges7676 bronze badges
MichaelMichael28.8k1414 gold badges6666 silver badges9898 bronze badges
In Java 7 and up:
There are useful utilities for that though:
- FileUtils.writeStringtoFile(.) from commons-io
- Files.write(.) from guava
Note also that you can use a
FileWriter
, but it uses the default encoding, which is often a bad idea - it's best to specify the encoding explicitly.Below is the original, prior-to-Java 7 answer
See also: Reading, Writing, and Creating Files (includes NIO2).
Peter Mortensen14.2k1919 gold badges8888 silver badges115115 bronze badges
BozhoBozho499k112112 gold badges971971 silver badges10831083 bronze badges
If you already have the content you want to write to the file (and not generated on the fly), the
java.nio.file.Files
addition in Java 7 as part of native I/O provides the simplest and most efficient way to achieve your goals.Basically creating and writing to a file is one line only, moreover one simple method call!
The following example creates and writes to 6 different files to showcase how it can be used:
iczaicza190k2828 gold badges398398 silver badges416416 bronze badges
Eric PetroeljeEric Petroelje52.9k88 gold badges108108 silver badges168168 bronze badges
Here's a little example program to create or overwrite a file. It's the long version so it can be understood more easily.
Nic Hartley4,68077 gold badges3838 silver badges5858 bronze badges
DraevenDraeven
Use:
Using
try()
will close stream automatically. This version is short, fast (buffered) and enables choosing encoding. This feature was introduced in Java 7.
Peter Mortensen14.2k1919 gold badges8888 silver badges115115 bronze badges
icl7126icl71262,11211 gold badge3131 silver badges3333 bronze badges
A very simple way to create and write to a file in Java:
Reference: File create Example in java
Peter Mortensen14.2k1919 gold badges8888 silver badges115115 bronze badges
Anuj DhimanAnuj Dhiman1,06611 gold badge1212 silver badges3131 bronze badges
Here we are entering a string into a text file:
We can easily create a new file and add content into it.
Peter Mortensen14.2k1919 gold badges8888 silver badges115115 bronze badges
iKingiKing
If you wish to have a relatively pain-free experience you can also have a look at the Apache Commons IO package, more specifically the
FileUtils
class.Never forget to check third-party libraries. Joda-Time for date manipulation, Apache Commons Lang
StringUtils
for common string operations and such can make your code more readable. Java is a great language, but the standard library is sometimes a bit low-level. Powerful, but low-level nonetheless.
Rory O'Kane19.4k88 gold badges6767 silver badges110110 bronze badges
extraneonextraneon19.9k22 gold badges3838 silver badges4949 bronze badges
Since the author did not specify whether they require a solution for Java versions that have been EoL'd (by both Sun and IBM, and these are technically the most widespread JVMs), and due to the fact that most people seem to have answered the author's question before it was specified that it is a text (non-binary) file, I have decided to provide my answer.
First of all, Java 6 has generally reached end of life, and since the author did not specify he needs legacy compatibility, I guess it automatically means Java 7 or above (Java 7 is not yet EoL'd by IBM). So, we can look right at the file I/O tutorial: https://docs.oracle.com/javase/tutorial/essential/io/legacy.html
Prior to the Java SE 7 release, the java.io.File class was the mechanism used for file I/O, but it had several drawbacks.
- Many methods didn't throw exceptions when they failed, so it was impossible to obtain a useful error message. For example, if a file deletion failed, the program would receive a 'delete fail' but wouldn't know if it was because the file didn't exist, the user didn't have permissions, or there was some other problem.
- The rename method didn't work consistently across platforms.
- There was no real support for symbolic links.
- More support for metadata was desired, such as file permissions, file owner, and other security attributes. Accessing file metadata was inefficient.
- Many of the File methods didn't scale. Requesting a large directory listing over a server could result in a hang. Large directories could also cause memory resource problems, resulting in a denial of service.
- It was not possible to write reliable code that could recursively walk a file tree and respond appropriately if there were circular symbolic links.
Oh well, that rules out java.io.File. If a file cannot be written/appended, you may not be able to even know why.
We can continue looking at the tutorial: https://docs.oracle.com/javase/tutorial/essential/io/file.html#common
Download new and previously released drivers including support software, bios, utilities, firmware and patches for Intel products. Use Driver Easy Free to download and install Intel(R) Management Engine Interface driver immediately! You may have seen Intel Management Engine Interface (IMEI) somewhere in your computer before but you’re not sure what it is or what it does.No worries, you’re not alone. Actually, it’s quite an important device. It works to make sure that your PC is running at its peak performance. Intel management engine interface driver windows 10. This package provides Intel Management Engine Interface Driver and is supported on OptiPlex, Precision, XPS and Latitude running the following Operating Systems: Windows 7 32bits/64bits, Windows 8.1 32bits/64bits, Windows 10 32bits/64bits. Mar 28, 2016 This download record installs the Intel® Management Engine (Intel® ME) components for Windows 7., 8.1., and Windows® 10 for Intel® NUC Kit NUC5i5MYHE and Intel® NUC Board NUC5i5MYBE. This folder contains the installer for the Intel Management Engine Interface driver only. Intel® Converged Security and Management Engine, Intel® Server Platform Services, Intel® Trusted Execution Engine, and Intel® Active Management Technology Advisory (Intel-SA-00185). Why is the Intel® Driver & Support Assistant unable to update the Intel® Management Engine driver? Intel® Management Engine Critical Firmware Update.
If you have all lines you will write (append) to the text file in advance, the recommended approach ishttps://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#write-java.nio.file.Path-java.lang.Iterable-java.nio.charset.Charset-java.nio.file.OpenOption..-
Here's an example (simplified):
Another example (append):
If you want to write file content as you go:https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#newBufferedWriter-java.nio.file.Path-java.nio.charset.Charset-java.nio.file.OpenOption..-
Simplified example (Java 8 or up):
Another example (append):
These methods require minimal effort on the author's part and should be preferred to all others when writing to [text] files.
Peter Mortensen14.2k1919 gold badges8888 silver badges115115 bronze badges
afk5minafk5min
If you for some reason want to separate the act of creating and writing, the Java equivalent of
touch
iscreateNewFile()
does an existence check and file create atomically. This can be useful if you want to ensure you were the creator of the file before writing to it, for example.69k1212 gold badges143143 silver badges179179 bronze badges
Peter Mortensen14.2k1919 gold badges8888 silver badges115115 bronze badges
Rohit ZPRohit ZP
Peter Mortensen14.2k1919 gold badges8888 silver badges115115 bronze badges
benben36511 gold badge66 silver badges2323 bronze badges
Here are some of the possible ways to create and write a file in Java :
Using FileOutputStream
Using FileWriter
Using PrintWriter
Using OutputStreamWriter
For further check this tutorial about How to read and write files in Java .
MehdiMehdi
Peter Mortensen14.2k1919 gold badges8888 silver badges115115 bronze badges
aashimaaashima
suresh manda52711 gold badge77 silver badges2424 bronze badges
Anurag GoelAnurag Goel
yole64.2k1212 gold badges171171 silver badges152152 bronze badges
Suthan SrinivasanSuthan Srinivasan
best way is to use Java7:Java 7 introduces a new way of working with the filesystem, along with a new utility class – Files. Using the Files class, we can create, move, copy, delete files and directories as well; it also can be used to read and write to a file.
Write with FileChannelIf you are dealing with large files, FileChannel can be faster than standard IO. The following code write String to a file using FileChannel:
Write with DataOutputStream
Write with FileOutputStream
Let’s now see how we can use FileOutputStream to write binary data to a file. The following code converts a String int bytes and writes the bytes to file using a FileOutputStream:
Write with PrintWriterwe can use a PrintWriter to write formatted text to a file:
Write with BufferedWriter:use BufferedWriter to write a String to a new file:
append a String to the existing file:
sajad abbasisajad abbasi69622 gold badges77 silver badges2424 bronze badges
JonasCz9,70155 gold badges3131 silver badges5353 bronze badges
Ran AdlerRan Adler
The simplest way I can find:
It will probably only work for 1.7+.
Peter Mortensen14.2k1919 gold badges8888 silver badges115115 bronze badges
qedqed10.6k1212 gold badges7272 silver badges130130 bronze badges
If we are using Java 7 and above and also know the content to be added (appended) to the file we can make use of newBufferedWriter method in NIO package.
There are few points to note:
- It is always a good habit to specify charset encoding and for that we have constant in class
StandardCharsets
. - The code uses
try-with-resource
statement in which resources are automatically closed after the try.
Though OP has not asked but just in case we want to search for lines having some specific keyword e.g.
i_am_zeroi_am_zeroconfidential
we can make use of stream APIs in Java:13.6k44 gold badges6363 silver badges6262 bronze badges
File reading and writing using input and outputstream:
Peter Mortensen14.2k1919 gold badges8888 silver badges115115 bronze badges
Anurag GoelAnurag Goel
Just include this package:
And then you can use this code to write the file:
Peter Mortensen14.2k1919 gold badges8888 silver badges115115 bronze badges
user4880283
It's worth a try for Java 7+:
It looks promising..
Peter Mortensen14.2k1919 gold badges8888 silver badges115115 bronze badges
Java Write To File Outputstream
Olu SmithOlu Smith
Peter Mortensen14.2k1919 gold badges8888 silver badges115115 bronze badges
imvpimvp
You can even create a temporary file using a system property, which will be independent of which OS you are using.
Peter Mortensen14.2k1919 gold badges8888 silver badges115115 bronze badges
Muhammed SayeedMuhammed Sayeed
In Java 8 use Files and Paths and using try-with-resources construct.
praveenraj4everpraveenraj4ever19611 gold badge22 silver badges1212 bronze badges
Using Google's Guava library, we can create and write to a file very easily.
The example creates a new
Jan BodnarJan Bodnarfruits.txt
file in the project root directory.4,86611 gold badge2929 silver badges4242 bronze badges
Reading collection with customers and saving to file, with JFilechooser.
Peter Mortensen14.2k1919 gold badges8888 silver badges115115 bronze badges
hasskellhasskell
Peter Mortensen14.2k1919 gold badges8888 silver badges115115 bronze badges
sultansultan
protected by user207421Nov 26 '16 at 1:27
Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
Would you like to answer one of these unanswered questions instead?
Not the answer you're looking for? Browse other questions tagged javafile-io or ask your own question.
The File class is Java’s representation of a file or directory path name. Because file and directory names have different formats on different platforms, a simple string is not adequate to name them. The File class contains several methods for working with the path name, deleting and renaming files, creating new directories, listing the contents of a directory, and determining several common attributes of files and directories.
Java Write To File Csv
- It is an abstract representation of file and directory pathnames.
- A pathname, whether abstract or in string form can be either absolute or relative. The parent of an abstract pathname may be obtained by invoking the getParent() method of this class.
- First of all, we should create the File class object by passing the filename or directory name to it. A file system may implement restrictions to certain operations on the actual file-system object, such as reading, writing, and executing. These restrictions are collectively known as access permissions.
- Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change.
How to create a File Object?
A File object is created by passing in a String that represents the name of a file, or a String or another File object. For example,
A File object is created by passing in a String that represents the name of a file, or a String or another File object. For example,
defines an abstract file name for the geeks file in directory /usr/local/bin. This is an absolute abstract file name.
Constructors
- File(File parent, String child) : Creates a new File instance from a parent abstract pathname and a child pathname string.
- File(String pathname) : Creates a new File instance by converting the given pathname string into an abstract pathname.
- File(String parent, String child) : Creates a new File instance from a parent pathname string and a child pathname string.
- File(URI uri) : Creates a new File instance by converting the given file: URI into an abstract pathname.
Methods
- boolean canExecute() : Tests whether the application can execute the file denoted by this abstract pathname.
- boolean canRead() : Tests whether the application can read the file denoted by this abstract pathname.
- boolean canWrite() : Tests whether the application can modify the file denoted by this abstract pathname.
- int compareTo(File pathname) : Compares two abstract pathnames lexicographically.
- boolean createNewFile() : Atomically creates a new, empty file named by this abstract pathname .
- static File createTempFile(String prefix, String suffix) : Creates an empty file in the default temporary-file directory.
- boolean delete() : Deletes the file or directory denoted by this abstract pathname.
- boolean equals(Object obj) : Tests this abstract pathname for equality with the given object.
- boolean exists() : Tests whether the file or directory denoted by this abstract pathname exists.
- String getAbsolutePath() : Returns the absolute pathname string of this abstract pathname.
- long getFreeSpace() : Returns the number of unallocated bytes in the partition .
- String getName() : Returns the name of the file or directory denoted by this abstract pathname.
- String getParent() : Returns the pathname string of this abstract pathname’s parent.
- File getParentFile() : Returns the abstract pathname of this abstract pathname’s parent.
- String getPath() : Converts this abstract pathname into a pathname string.
- boolean isDirectory() : Tests whether the file denoted by this pathname is a directory.
- boolean isFile() : Tests whether the file denoted by this abstract pathname is a normal file.
- boolean isHidden() : Tests whether the file named by this abstract pathname is a hidden file.
- long length() : Returns the length of the file denoted by this abstract pathname.
- String[] list() : Returns an array of strings naming the files and directories in the directory .
- File[] listFiles() : Returns an array of abstract pathnames denoting the files in the directory.
- boolean mkdir() : Creates the directory named by this abstract pathname.
- boolean renameTo(File dest) : Renames the file denoted by this abstract pathname.
- boolean setExecutable(boolean executable) : A convenience method to set the owner’s execute permission.
- boolean setReadable(boolean readable) : A convenience method to set the owner’s read permission.
- boolean setReadable(boolean readable, boolean ownerOnly) : Sets the owner’s or everybody’s read permission.
- boolean setReadOnly() : Marks the file or directory named so that only read operations are allowed.
- boolean setWritable(boolean writable) : A convenience method to set the owner’s write permission.
- String toString() : Returns the pathname string of this abstract pathname.
- URI toURI() : Constructs a file URI that represents this abstract pathname.
Implementation
Program 1: Program to check if a file or directory physically exist or not.
// In this program, we accepts a file or directory name from // command line arguments. Then the program will check if // that file or directory physically exist or not and // it displays the property of that file or directory. class fileProperty public static void main(String[] args) { //accept file name or directory name through command line args //pass the filename or directory name to File object System.out.println( 'File name :' +f.getName()); System.out.println( 'Absolute path:' +f.getAbsolutePath()); System.out.println( 'Exists :' +f.exists()); { System.out.println( 'Is writeable:' +f.canWrite()); System.out.println( 'Is a directory:' +f.isDirectory()); System.out.println( 'File Size in bytes ' +f.length()); } |
Output:
Program 2: Program to display all the contents of a directory
Here we will accept a directory name from the keyboard and then display all the contents of the directory .For this purpose, list() method can be used as:
In the preceding statement , the list() method causes all the directory entries copied into the array arr[]. Then pass these array elements arr[i] to File object and test them to know if they represent a file or directory .
import java.io.File; import java.io.InputStreamReader; //Displaying the contents of a directory { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); System.out.println( 'Enter dirpath:' ); System.out.println( 'Enter the dirname' ); File f = new File(dirpath, dname); //if directory exists,then { //now arr[i] represent either a File or Directory int n=arr.length; //displaying the entries System.out.println(arr[i]); //if it is a file or directory if (f1.isFile()) if (f1.isDirectory()) } System.out.println( 'No of entries in this directory ' +n); else } |
Output:
Related Post :FileReader and FileWriter in Java
This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.