Java read multiple files


 

Java read multiple files

In this section you will learn how to read the data of multiple files.

In this section you will learn how to read the data of multiple files.

Java read multiple files

In this section you will learn how to read the data of multiple files. Here we have created four files that includes information of students of a class. Each file contains a student's name, email, school and hobby. We have to find the students according to particular school from all the files and write all the information of the students belongs to same school into a single file.

Here is the code:

import java.io.*;
import java.util.*;

public class Files {
	public static void main(String[] args) throws Exception {
		Scanner input = new Scanner(System.in);
		System.out.println("Enter school Name");
		String sch = input.nextLine();
		String fname[] = { "s1.txt", "s2.txt", "s3.txt", "s4.txt" };
		File file = new File("data.txt");
		FileWriter fstream = new FileWriter(file, true);
		BufferedWriter out = new BufferedWriter(fstream);

		for (int i = 0; i < fname.length; i++) {
			File f = new File(fname[i]);
			try {
				BufferedReader freader = new BufferedReader(new FileReader(f));
				String s;
				while ((s = freader.readLine()) != null) {
					String[] st = s.split(" ");
					String name = st[0];
					String email = st[1];
					String school = st[2];
					String hobby = st[3];
					if (school.equals(sch)) {
						System.out.println(name + " " + email + " " + hobby);
						out.write(name + " " + email + " " + school + " "
								+ hobby);
						out.newLine();
					}
				}
				freader.close();
			} catch (Exception e) {
			}
		}
		out.close();

	}
}

Ads