Nexus_Valentine
Nexus_Valentine

Reputation: 158

How to create more than one file in specified directory's?

I have created the first file but I was wondering how to create a second and so on if i desired?

public class Test {
      public static void main(String[] args) {
        try {
          File myObj = new File("C:\\Users\\sarah\\OneDrive\\Documents\\input.txt");
          File myObj2 = new File("C:\\Users\\sarah\\OneDrive\\Documents\\output.txt");
          if (myObj.createNewFile()) {
            System.out.println("File created: " + myObj.getName());
          } else {
            System.out.println("File already exists.");
          }
        } catch (IOException e) {
          System.out.println("An error occurred.");
          e.printStackTrace();
        }
      }
    }

Upvotes: 1

Views: 39

Answers (1)

user2222
user2222

Reputation: 474

import java.io.*;
public class Main{

    public static void main(String[] args) {
        File[] fileList = {new File("C:\\Users\\sarah\\OneDrive\\Documents\\input.txt"),
             new File("C:\\Users\\sarah\\OneDrive\\Documents\\output.txt")};
        try {
            for (File file : fileList) {
                if (file.createNewFile()) {
                    System.out.println("File created: " + file.getName());
                } else {
                    System.out.println("File already exists.");
                }
            }
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

Upvotes: 1

Related Questions