0% found this document useful (0 votes)
13 views5 pages

java_io

The document contains multiple Java classes that perform various file operations, including writing data to files, calculating age from a birthday read from a file, calculating average profits, and managing exam grades. Each class demonstrates different functionalities such as reading from and writing to files, calculating statistics, and handling exceptions. Overall, it showcases practical applications of file handling and data processing in Java.

Uploaded by

czxc650
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views5 pages

java_io

The document contains multiple Java classes that perform various file operations, including writing data to files, calculating age from a birthday read from a file, calculating average profits, and managing exam grades. Each class demonstrates different functionalities such as reading from and writing to files, calculating statistics, and handling exceptions. Overall, it showcases practical applications of file handling and data processing in Java.

Uploaded by

czxc650
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

package test;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Test {

public static void main(String[] args) {

String fileName = "test.txt";


String data = "java is language";
writeFile(fileName, data);

File f = new File(fileName);

System.out.println("File Size (bytes): " + f.length());


System.out.println("File Size (KB): " + (f.length() / 1024.0));
System.out.println("File Size (MB): " + (f.length() / (1024.0 * 1024)));
}

public static void writeFile(String fileName, String data) {


try (FileWriter writer = new FileWriter(fileName)) {
writer.write(data);
} catch (IOException e) {
}
}
}
--------------------------------------------------
package date;

import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Scanner;

public class AgeCalculator {

public static void main(String[] args) {


String fileName = "date.txt";
LocalDate birthday = readBirthdayFromFile(fileName);

if (birthday != null) {
int age = calculateAge(birthday);
System.out.println("Your age is: " + age);
} else {
System.out.println("Failed to read birthday from file.");
}
}

public static LocalDate readBirthdayFromFile(String fileName) {


try (Scanner scanner = new Scanner(new File(fileName))) {
String dateString = scanner.nextLine().trim();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d / M /
yyyy");
return LocalDate.parse(dateString, formatter);
} catch (FileNotFoundException e) {
System.out.println("File not found: " + fileName);
return null;
}
}

public static int calculateAge(LocalDate birthday) {


return (int) ChronoUnit.YEARS.between(birthday, LocalDate.now());
}
}
-------------------------------------------
package profitcalculator;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class ProfitCalculator {
public static void main(String[] args) {
int[] profits = {10000, 50000, 25000};
writeProfitsToFile("profit.txt", profits);
double averageProfit = calculateAverageProfit("profit.txt");
System.out.println("Average profit: $" + averageProfit);
}
public static void writeProfitsToFile(String fileName, int[] profits) {
try (FileWriter writer = new FileWriter(fileName)) {
for (int profit : profits) {
writer.write(profit + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static double calculateAverageProfit(String fileName) {
try (Scanner scanner = new Scanner(new File(fileName))) {
int sum = 0;
int count = 0;
while (scanner.hasNextInt()) {
sum += scanner.nextInt();
count++;
}
if (count > 0) {
return (double) sum / count;
} else {
return 0; // Avoid division by zero
}
} catch (IOException e) {
e.printStackTrace();
return 0;
}
}
}
--------------------------------------------------
package examgrades;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class ExamGrades {
public static void main(String[] args) {
int[] grades = {40, 44, 60, 59, 35};
writeGradesToFile("degrees.txt", grades);
System.out.println("Largest degree: " + findExtremeDegree("degrees.txt",
true));
System.out.println("Lowest degree: " + findExtremeDegree("degrees.txt",
false));
System.out.println("Number of successful students: " +
countSuccessfulStudents("degrees.txt"));
}
public static void writeGradesToFile(String fileName, int[] grades) {
try (FileWriter writer = new FileWriter(fileName)) {
for (int grade : grades) {
writer.write(grade + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static int findExtremeDegree(String fileName, boolean isLargest) {
int extreme = isLargest ? Integer.MIN_VALUE : Integer.MAX_VALUE;
try (Scanner scanner = new Scanner(new File(fileName))) {
while (scanner.hasNextInt()) {
int grade = scanner.nextInt();
if (isLargest && grade > extreme) {
extreme = grade;
} else if (!isLargest && grade < extreme) {
extreme = grade;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return extreme;
}
public static int countSuccessfulStudents(String fileName) {
int count = 0;
try (Scanner scanner = new Scanner(new File(fileName))) {
while (scanner.hasNextInt()) {
if (scanner.nextInt() >= 40) {
count++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return count;
}
}
--------------------------------------------
package fileoperations;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class FileOperations {
public static void main(String[] args) {
String filePath = "data.txt";
String newPath = "newData.txt";
copyFile(filePath, newPath);
renameFile(newPath, "renamedData.txt");
}
public static void copyFile(String sourcePath, String destinationPath) {
try {
File sourceFile = new File(sourcePath);
File destinationFile = new File(destinationPath);
Files.copy(sourceFile.toPath(), destinationFile.toPath(),
StandardCopyOption.REPLACE_EXISTING);
System.out.println("File copied successfully from " + sourcePath + " to
" + destinationPath);
} catch (IOException e) {
}
}
public static void renameFile(String filePath, String newName) {
try {
File file = new File(filePath);
File newFile = new File(file.getParent(), newName);
if (file.renameTo(newFile)) {
System.out.println("File renamed successfully to " + newName);
} else {
System.out.println("Failed to rename the file");
}
} catch (Exception e) {
}
}
}
--------------------------------
package salarycalculator;
import java.io.*;
import java.util.*;
public class EmployeeSalaries {
public static void main(String[] args) {
int[] salaries = {1000, 2000, 3000, 4000, 5000, 6000};

try (BufferedWriter writer = new BufferedWriter(new


FileWriter("salary.txt"))) {
for (int salary : salaries) {
writer.write(salary + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
List<Integer> salaryList = new ArrayList<>();
try (Scanner scanner = new Scanner(new File("salary.txt"))) {
while (scanner.hasNextInt()) {
salaryList.add(scanner.nextInt());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}

// Determine the number of employees who receive a salary less than 3500
pounds
int count = 0;
for (int salary : salaryList) {
if (salary < 3500) {
count++;
int increase = 3500 - salary;
System.out.println("Employee with salary " + salary + " needs an
increase of " + increase + " pounds to reach 3500 pounds.");
}
}
System.out.println("Number of employees with salary less than 3500 pounds:
" + count);
}
}

You might also like