JAVA Streams and Writers:
FILE WRITING
Sample Input:
[All Texts in bold corresponds to the input and rest are output]
Enter the number of users:
3
Enter the details of user :1
Jane,1234,jane,jane
Enter the details of user :2
John,5678,john,john
Enter the details of user :3
Jill,1357,jill,jill
[All Texts in bold corresponds to the input and rest are output]
Enter the number of users:
3
Enter the details of user :1
Jane,1234,jane,jane
Enter the details of user :2
John,5678,john,john
Enter the details of user :3
Jill,1357,jill,jill
CODE:
public class User {
String name;
String mobileNumber;
String username;
String password;
public User(String name,String mobileNumber,String username,String password)
{
this.name=name;
this.mobileNumber=mobileNumber;
this.username=username;
this.password=password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
import java.util.*;
import java.io.*;
//static method- only one copy of method in class
public class UserBO {
public static void writeFile(ArrayList<User> userList, BufferedWriter bw) throws Exception {
for(int i=0; i<userList.size(); i++) {
String rec = (userList.get(i)).getName()+","+userList.get(i).getMobileNumber()+","+userList.get(i).getUsername()+","+userList.get(i).getPassword()+"\n";
bw.write(rec);
bw.flush();-
}
bw.close();
}
}
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String args[]) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of users:");
int num = Integer.parseInt(sc.nextLine());
ArrayList<User> al = new ArrayList<User>();
FileWriter fw = new FileWriter("output.csv");
BufferedWriter bw = new BufferedWriter(fw);
for(int i=1; i<=num; i++) {
System.out.println("Enter the details of user :"+i);
String record = sc.nextLine();
String values[]=record.split(",");
User user = new User(values[0],values[1],values[2],values[3]);
al.add(user);
user=null;
}
try {
UserBO.writeFile(al, bw);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Comments
Post a Comment