Read all the files from a folder starting from 2nd file in Java

read file from folder in java example
java get all files in directory and subdirectories
java get all files in directory with extension
java merge all files in directory
java get all files in directory and sub-directories java 8
for(file f files)
java list files in directory recursively
read all files in a directory java mkyong

I have few files in a folder and I want to read the first file and perform some operations and after the first iteration, I want to read files from the 2nd one on wards to perform different set of operations.

How can I do this?

    File folder=new File(Folder);            
    File[] listOfFiles=folder.listFiles();          

        for(File file:listOfFiles)
            //Do something
        //Here I want to read from the 2nd file to do different set of operations

Get the first file as listOfFiles[0] and do the operation1 on it.

Then, use a simple (regular) for loop starting at index 1.

for (int i = 1; i < listOfFiles.length; i++) {
   File currentFile = listOfFiles[i];
   //do Operation 2 with currentFile

Note from the javadoc of Files.listFiles

There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.

UGC NET CS Notes Paper II · UGC NET CS Notes Paper III · UGC NET CS Solved Papers Loop for reading the contents of all the files in the directory GeeksForGeeks. Create instance of file from Name of the file stored in string Array. Moving a file from one directory to another using Java · How to run java class file  In that method while going through the list of files under a folder you check if the next element of the list is a file or a folder. If it is a folder then you recursively call the listAllFiles () method with that folder name. If it is a file you call the readContent () method to read the file using BufferedReader.

As per your comment, it seems like you don't need the list of files to be sorted in some particular order before you process them. In that case,

File folder=new File(Folder);            
File[] listOfFiles=folder.listFiles();          

//use a normal for loop to keep track of the index
for(int i=0; i<listOfFiles.length; i++){
   //the file in the current index of iteration
   File currentFile = listOfFiles[i];
      //Do something with first file
      //Here I want to read from the 2nd file to do different set of operations

In the above code put the operation code for first file in the if block and the code for rest of the files in else block

Below example shows how to get list of all file names from the given folder. First create File object by How to read file content line by line in java? How to read  Java 8 How to Read all files in a folder: Java 7 introduced Files class that consists exclusively of static methods that operate on files, directories, or other types of data. From Java 8 Walk method was introduced as part of Files class which is used to read the files under the specified path or directory.

Don't use anymore, use java.nio—it's been around for a couple of years now! Beside the easier use—including Java 8 streams, one benefit is that you're not restricted to the system's default file system. You might even use an in-memory file system like Google's JimFS. As pointed out by other's, there is no guarantee on the order of files. You may however introduce your own sorting:

FileSystem fs = FileSystems.getDefault(); // use a file system of your choice here!
Path folder = fs.getPath(...);

     .sorted((a, b) -> { ... })
     // this realizes the skipping of the first element you initially requested:
     .forEach(f -> { ... });

If you want to perform action A on the first element and action B on the second, it might get a litle trickier: you might define a boolean firstFileHasBeenProcessed as external dependency, that's gonna be set to true once you processed the first file, but I am not sure if the consumers for all files will run strictly sequential—or if the processing of the first file may be interrupted to start processing the seond, before that flag could be set.

You can always render a stream to an array ...

final Path[] allFiles = Files.newDirectoryStream(folder)
                      .sorted((a, b) -> { ... })

... or a list, though, to gain more control.

final List<Path> allFiles = Files.newDirectoryStream(folder)
                          .sorted((a, b) -> { ... })

boolean firstHasBeenProcessed = false;
for (final Path currentFile: allFiles) {
    if (firstHasBeenProcessed) {
    } else {
        firstHasBeenProcessed = true;

The class named File of the package represents a file or directory How to read the data from a properties file in Java? To get the list of all the existing files in a directory this class provides the files class IOException { //Creating a File object for directory File directoryPath Published on 02-Aug-2019 14:31:52. Extract list of files belonging to specific file type. Extract list of files belonging to specific file type, present in the folder and its sub folders/directories. How to extract list of files and directories in a folder using java ? Step 1 : Specify the folder. In this example, “sample” is the folder name placed at the root to the project.

the first one will list all the files and folder names under a directory; the second one will list File;. /**. * Contains some methods to list files and folders from a directory //get all the files from a directory DZone > Java Zone > How to Get a Record From the Database Using JdbcTemplate With Spring Boot  Although there is no profound delimiter to set fields apart from one another it appears that each field consists of a specific length (CourseID = 4, CourseName = 20, Creadits = 1, StudentName = 10, Major = 20, and finally Grade = 1). Based on this you can easily pull apart and trim each file line as it is read from file.

But how do you list all the directories at the top of a file system? Listing a File System's Root Directories; Creating a Directory; Creating a Temporary location for the temporary directory and the second method creates a new directory in the​  Let's say, I have a folder called maps and inside maps I have map1.txt, map2.txt, and map3.txt. How can I use Java and the BufferReader to read all of the .txt files in folder maps (if it is at all

java.nio.file. Let's describe each method starting with Files.list() . to use it in a try-with-resources and throws an exception if it cannot read a file or directory. The class named File of the package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories. To get the list of all the existing files in a directory this class provides the files class provides list () (returns names) and ListFiles (returns File

  • Understand that there is no guarantee in the order of the files, running the code twice could generate two different results
  • What is the first file according to your requirement? Is it the first file sorted alphabetically?
  • No. Its just few XML files where I should read each XML file from the folder to generate the report. Basically I need to compare the results of each XML in two different environment. So, when I read the first file, it should open both the environments in a window .. So now it has 2 tabs open, and from 2nd file on wards I should just continue the execution without opening a new window and login and stuff.
  • use a variable to save the environment (e.g. the window) and start with null. In the loop, if it is null, create and assign the environment. After the first time, the variable will not be null and so that operation is only executed once (and it is quite clear for any one reading the code). Eventually you can/should use just a boolean flag instead of the environment...
  • But I'm using the file name for few things. In that case, how can I extract the file name? If I use for(File file:listOfFiles), I can get the filename "file".
  • I don't understand your question. listOfFiles[i] will give you a File
  • Yes I do know to use Arrays
  • @JavaUser Inside the loop use file.getName() to retrieve the name of the file