सूचीफ़ाइलें() फ़ाइल . की विधि क्लास वर्तमान (फाइल) ऑब्जेक्ट द्वारा दर्शाए गए पथ में सभी फाइलों (और निर्देशिकाओं) के ऑब्जेक्ट्स (अमूर्त पथ) को पकड़ने वाला एक सरणी देता है।
एक फ़ोल्डर में सभी फाइलों की सामग्री को एक फाइल में पढ़ने के लिए -
- आवश्यक फ़ाइल पथ को पैरामीटर के रूप में पास करके फ़ाइल ऑब्जेक्ट बनाएं।
- स्कैनर या किसी अन्य पाठक का उपयोग करके प्रत्येक फ़ाइल की सामग्री पढ़ें।
- पढ़ी गई सामग्री को StringBuffer में जोड़ें।
- स्ट्रिंगबफ़र सामग्री को आवश्यक आउटपुट फ़ाइल में लिखें।
उदाहरण
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class Test {
public static void main(String args[]) throws IOException {
//Creating a File object for directory
File directoryPath = new File("D:\\SampleDirectory");
//List of all files and directories
File filesList[] = directoryPath.listFiles();
System.out.println("List of files and directories in the specified directory:");
Scanner sc = null;
StringBuffer sb = new StringBuffer();
for(File file : filesList) {
System.out.println("File name: "+file.getName());
System.out.println("File path: "+file.getAbsolutePath());
System.out.println("Size :"+file.getTotalSpace());
//Instantiating the Scanner class
sc= new Scanner(file);
String input;
while (sc.hasNextLine()) {
input = sc.nextLine();
sb.append(input+" ");
}
System.out.println("Contents of the file: "+sb.toString());
System.out.println(" ");
//Instantiating the FileOutputStream class
FileOutputStream fileOut = new FileOutputStream("D:\\output.txt");
//Instantiating the DataOutputStream class
DataOutputStream outputStream = new DataOutputStream(fileOut);
//Writing UTF data to the output stream
outputStream.write(sb.toString().getBytes());
outputStream.flush();
System.out.println("Data entered into the file");
}
}
} आउटपुट
List of files and directories in the specified directory: File name: sample1.txt File path: D:\SampleDirectory\sample1.txt Contents of the file: sample text file1 Data entered into the file File name: sample2.txt File path: D:\SampleDirectory\sample2.txt Contents of the file: sample text file2 Data entered into the file File name: sample3.txt File path: D:\SampleDirectory\sample3.txt Contents of the file: sample text file3 Data entered into the file