0% found this document useful (0 votes)
9 views7 pages

Java File Operations and Conversions

The document describes a Java program that can merge the contents of multiple text files into a single output file. It takes an array of file names as input and writes the merged content to a new output file, handling exceptions if any file is not found or there are input/output errors.

Uploaded by

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

Java File Operations and Conversions

The document describes a Java program that can merge the contents of multiple text files into a single output file. It takes an array of file names as input and writes the merged content to a new output file, handling exceptions if any file is not found or there are input/output errors.

Uploaded by

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

1. program that merges the contents of multiple text files into a single text file.

Solution:-

package c1;

import [Link].*;

public class Excep {

public static void main(String[] args) {

File[] files = new File[3];

File file1 = new File("D:\\[Link]");

File file2 = new File("D:\\[Link]");

File file3 = new File("D:\\[Link]");

files[0] = file1;

files[1] = file2;

files[2] = file3;

File merge = new File("D:\\[Link]");

mergeFiles(files, merge);

private static void mergeFiles(File[] files, File merge) {

try (BufferedWriter writer = new BufferedWriter(new FileWriter(merge))) {

for (File fileName : files) {

try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {

String line = "";

while ((line = [Link]()) != null) {

[Link](line);

[Link]();

[Link]("\n");

} catch (IOException e) {
[Link]("Error reading file: " + fileName);

[Link]();

[Link]("Files merged successfully into " + merge);

} catch (IOException e) {

[Link]("Error creating merged file: " + merge);

[Link]();

Input:- multiple file names

Output:- merged file

2. write java program that reads the contents of a file and handles exceptions for file not found
and input-output errors.

Solution:-

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class Excep {

public static void main(String[] args) {

File file = new File("D:\\[Link]");

BufferedReader reader = null;

try {

reader = new BufferedReader(new FileReader(file));

String line;
while ((line = [Link]()) != null)

[Link](line);

} catch (FileNotFoundException e)

[Link]("File not found: " + file);

} catch (IOException e)

[Link]("Error reading the file: " + [Link]());

Input:- input file

Output:- data

3. Write a java code using object, class, inheritance, polymorphism, abstraction and
encapsulation.

Solution:-

class Teacher

String name;

int age;

int salary;

Teacher()

Teacher(String name,int age,int salary)

{
[Link] =name;

[Link] = age;

[Link] = salary;

void role()

[Link]("Employee");

//Inheritance

class Student extends Teacher

String name;

int age;

int roll_no;

Student(String name,int age,int roll_no)

[Link] = name;

[Link] = age;

this.roll_no = roll_no;

//override

void role()

[Link]("Student");

}
}

public class Excep {

public static void main(String[] args)

Teacher t = new Teacher("vamsi",35,30000);

Student s = new Student("krishna",20,21);

[Link]();

4. Write a java program convert json file into csv file.


Solution:-
package c1;
import [Link].*;
import [Link].*;
import [Link];
import [Link].*;

public class Excep {

@SuppressWarnings("deprecation")
public static void main(String args[])
{

String jsonString;
JSONObject jsonObject;

try {

jsonString = new String(


[Link]([Link]("[Link]")));

jsonObject = new JSONObject(jsonString);

JSONArray docs
= [Link]("test");
File file = new File("C:\\[Link]");
String csvString = [Link](docs);
[Link](file, csvString);
}

catch (Exception e) {

[Link]();
}
}
}

5. Write a java program to convert csv to json file;


Solution:-
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class JsonToCsvConverter {

public static void main(String[] args) throws IOException, ParseException {

JSONParser parser = new JSONParser();

Object obj = [Link](new FileReader("json_file.json"));

JSONArray jsonArray = (JSONArray) obj;

List<String[]> csvData = new ArrayList<>();

for (int i = 0; i < [Link](); i++) {


JSONObject jsonObject = (JSONObject) [Link](i);

String name = (String) [Link]("name");


String age = (String) [Link]("age");
[Link](new String[]{name, age});
}
FileWriter writer = new FileWriter("csv_file.csv");

for (String[] row : csvData) {


[Link]([Link](",", row));
[Link]("\n");
}

[Link]();
}
}

Common questions

Powered by AI

Source 2's program handles exceptions by encapsulating the JSON parsing and file writing processes in try-catch blocks. It acknowledges ParseException for issues during JSON parsing and IOExceptions for file operations, ensuring that any parsing errors or file handling issues are caught and managed, preventing the program from crashing and allowing for troubleshooting based on logged error details .

Try-with-resources in Java automatically closes resources such as BufferedReader and BufferedWriter once they are no longer in use, even if exceptions are thrown. This feature, used in Source 1, ensures that file handles are released promptly, preventing resource leaks that can degrade performance or cause the program to run out of available resources for file operations. This automated closure reduces errors related to manual resource management .

Source 2 uses JSONParser from the org.json.simple library to parse JSON data. It iterates over each JSONObject in the JSONArray, extracting values associated with specific keys like "name" and "age". These values are stored in a List of string arrays, representing rows of CSV data. This list is then written to a file using FileWriter, converting the list of arrays into a CSV format by joining each array with commas .

Polymorphism is demonstrated through method overriding in the role method of the Student class, which extends the Teacher class. The Student class provides its own implementation of the role method, allowing an instance of Student to execute its unique behavior (printing "Student") instead of the inherited method from Teacher (which would print "Employee").

The program reads a JSON file using the java.nio and org.json libraries. It parses the JSON data and iterates over the contents using JSONArray. It converts this data into a CSV formatted string using CDL.toString() from the org.json library. The output CSV is then written to a file using FileUtils.writeStringToFile() provided by the Apache Commons IO library .

The program merges contents from multiple text files, specifically file1.txt, file2.txt, and file3.txt, into a single text file named merge.txt. It utilizes a BufferedWriter to write into the merge file and a BufferedReader to read from each input file in a loop, appending each line to the BufferedWriter. It incorporates error handling by catching IOExceptions during both reading and writing processes, ensuring that errors in file reading or creation are captured and logged properly .

When reading from a file, exceptions such as FileNotFoundException and IOException must be handled, capturing errors related to unavailable files or read errors. Conversely, when writing to a file, only IOExceptions related to the writing process need to be caught. Both operations use try-catch blocks, but specific exceptions are tailored to the nature of the operation—missing files versus write failures. Error messages are logged to provide insight into the specific operation failures .

The program demonstrates several OOP principles: inheritance, polymorphism, abstraction, and encapsulation. The Student class inherits from the Teacher class, showcasing inheritance. Polymorphism is shown through method overriding in the Student class' role method. Encapsulation is implemented through constructors that initialize object state, although the example does not fully demonstrate data hiding as it lacks private access modifiers and getter/setter methods .

The program ensures accuracy by accessing individual JSON objects within a JSONArray, extracting specific fields (e.g., "name" and "age"), and storing them as entries in a List of string arrays. This precise extraction and deliberate storage format align with the typical row-column structure of CSV, allowing precise writing into the CSV format using consistent array-element placement. This approach minimizes data discrepancy and format errors .

Challenges in merging files include handling IO exceptions during file reading and writing, managing correct file paths, and ensuring data integrity. The program addresses these challenges by using BufferedReader and BufferedWriter within try-catch blocks to manage IOExceptions. It checks for file existence before attempting operations and provides error logs if it encounters problems during read/write operations, helping to trace and resolve issues .

You might also like