Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

NAME: Abdul Moeed

REGISTRATION NUMBER: FA23-BSE-004

LAB: File Handiling

“Graded LAB Tasks”


Task 1:
Write a Java program to accept 10 integer values from user. Save this data in a file.

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

public class FileHandling {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
File file = new File("D:\\Programming fundamentals\\test.txt");
PrintStream ps = new PrintStream(file);
System.out.println("Enter the Integer values: ");
for (int i = 0; i < 10; i++) {
int values = sc.nextInt();
ps.println(values);
}
ps.close();
System.out.println("Data written in file");

Scanner fileReader = new Scanner(file);


System.out.println("Reading from file: ");
while (fileReader.hasNextInt()) {
int value = fileReader.nextInt();
System.out.println(value);
}
fileReader.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Task #02:
Write a Java program to accept all the data stored in a file in the previous task. Sort this data in
ascending order and display on screen.

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

public class FileHandling {


public static void main(String[] args) {
try {

File file = new File("D:\\Programming fundamentals\\test.txt");


Scanner fileReader = new Scanner(file);
List<Integer> values = new ArrayList<>();

while (fileReader.hasNextInt()) {
values.add(fileReader.nextInt());
}
fileReader.close();
Collections.sort(values);

System.out.println("Sorted values: ");


for (int value : values) {
System.out.println(value);
}

} catch (Exception e) {
System.out.println(e);
}
}
}
Task #03:
Write a Java program to accept all the data stored in a file in the previous task (Lab Task1).
Remove all the prime numbers from this data and save again in the same file.

import java.io.*;

import java.util.*;

public class A1{

public static void main(String[] args) {

try {

File file = new File("E:\\1. JAVA\\newfile.txt");

Scanner sc = new Scanner(file);

ArrayList<Integer> list = new ArrayList<>();

while (sc.hasNextInt()){

list.add(sc.nextInt());

//making a new array list to store the unPrimed numbers

ArrayList<Integer> unPrimedList = new ArrayList<>();

//checking and putting unPrimed numbers in unPrimed number list

for (Integer value : list) {

if (!IsPrime(value)) {

unPrimedList.add(value);

}
}

for (Integer integer : unPrimedList) {

System.out.println(integer);

catch (IOException e){

System.out.println(e);

public static boolean IsPrime(int number){

int check = 0;

for (int i=1;i<number;i++){

if (number%i==0) check++;

return check != 1;

You might also like