0% found this document useful (0 votes)
8 views2 pages

Java File Operations Example Code

The document contains Java code snippets for file operations including creating a file, writing to a file using FileInputStream, reading from a file using Scanner, and writing to an output file using BufferedWriter. Each code section is labeled with a question number and demonstrates basic file handling techniques in Java. The code includes error handling for file operations to manage exceptions.

Uploaded by

anishwarushe0725
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)
8 views2 pages

Java File Operations Example Code

The document contains Java code snippets for file operations including creating a file, writing to a file using FileInputStream, reading from a file using Scanner, and writing to an output file using BufferedWriter. Each code section is labeled with a question number and demonstrates basic file handling techniques in Java. The code includes error handling for file operations to manage exceptions.

Uploaded by

anishwarushe0725
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

ASSIGNMENT NO.

NAME - SHREEYA PRAVIN JOSHI

ROLL NO -57

PRN - 2122000723
Q1)

import [Link];
import [Link];
class CreateFile {
public static void main(String[] args) {
try {
File f= new File("C:\\Users\\Lenovo\\Desktop\\[Link]");
if ([Link]()) {
[Link]("File created: " + [Link]());
} else {
[Link]("File already exists.");
}
} catch (IOException e) {
[Link]("An error occurred.");
[Link]();
}
}
}

Q2 insert the content using fileinput stream

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

class WriteToFile {
public static void main(String[] args) {
try {
FileInputStream mywriter =new FileInputStream("[Link]");
//FileWriter myWriter = new FileWriter("[Link]");
[Link]("kit college is best in western maharastra");
[Link]();
[Link]("Successfully wrote to the file.");
} catch (IOException e) {
[Link]("An error occurred.");
[Link]();
}
}
}

Q3read the data for input file


import [Link];
import [Link];
import [Link];
class ReadFile {
public static void main(String[] args) {
try {
File myObj = new File("[Link]");
Scanner myReader = new Scanner(myObj);
while ([Link]()) {
String data = [Link]();
[Link](data);
}
[Link]();
} catch (FileNotFoundException e) {
[Link]("An error occurred.");
[Link]();
}
}
}

Q4 write the [Link] file using buffered class

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

class manish{
public static void main(String[] args)
throws IOException {

String manish= "Hello welcome to Scaler!";

try{
BufferedWriter f = new BufferedWriter(new FileWriter("[Link]"));

[Link](manish);

[Link]("[Link] file.");

[Link]();
}
catch (IOException e){

[Link](e);
}
}
}

Common questions

Powered by AI

The method createNewFile() attempts to create a new, empty file if a file with the specified pathname does not already exist. It returns a boolean value, true if the file was successfully created and false if the file already exists. This ensures that a program does not inadvertently overwrite existing files and confirms prior existence, which is essential for many file management tasks, like ensuring data integrity .

The Scanner class provides a convenient way to read files line by line in Java. It offers various methods for parsing primitive types and strings using regular expressions and supports reading from various sources, including input streams and files. In the ReadFile class, the Scanner class simplifies reading text data, handling line breaks automatically, and offers a simple nextLine method to retrieve each line of data efficiently .

Using FileInputStream incorrectly in the WriteToFile class might lead to unintended behavior since FileInputStream is typically used for reading binary data rather than writing text. The intended operation appears to be writing a string to a file, where FileWriter is more appropriate. If FileInputStream were used incorrectly here, it could cause runtime errors or data corruption due to misuse of stream types, highlighting a misunderstanding of Java's I/O stream capabilities .

Closing resources such as FileInputStream and BufferedWriter is crucial in preventing resource leaks, as these resources hold onto system-level handles. By closing them after use, as in the examples, the program returns these handles to the operating system, preventing memory leaks and ensuring efficient use of resources. Java's try-with-resources statement can automatically manage this closing process, ensuring resources are closed even if an exception occurs .

An IOException can be handled effectively by wrapping file operations in a try-catch block. The try block contains the potentially failing code, while the catch block contains logic to handle any IOError that might occur. This allows developers to manage error situations gracefully, such as creating error messages, logging errors, or performing cleanup processes as shown in the CreateFile and WriteToFile classes .

Using separate classes for different file operations follows the Single Responsibility Principle, a core concept in object-oriented design. Each class is responsible for a single aspect of file handling: creating a file, writing to it, or reading from it. This design makes the code more understandable, maintainable, and scalable. It allows modifications in one part of the file handling process without affecting others .

The ReadFile class handles a potential FileNotFoundException using a try-catch block. If the specified file 'input.txt' is not found, the catch block captures the exception and executes a set of instructions that provide information about the error, such as printing an error message and the stack trace. This approach ensures the program does not crash unexpectedly and allows troubleshooting without abrupt termination .

BufferedWriter is used for writing strings to a file more efficiently. Unlike FileWriter, which writes data directly to a file character by character, BufferedWriter stores data in a memory buffer and writes it to the file in larger chunks. This reduces the number of write operations to the file system, which enhances performance, especially for large files or when frequent write operations are necessary .

Not handling exceptions like IOException or FileNotFoundException in file operations can lead to several issues, including program crashes, data corruption, and poor user experiences. It can also make debugging difficult, as it is harder to determine where and why failures occur. Effective exception handling ensures that errors are caught, reported, and managed, allowing programs to recover gracefully or terminate with meaningful error messages .

The WriteToFile class may face compilation errors because the FileInputStream class is designed for reading bytes from a file, not writing. It does not provide a write() method, unlike FileOutputStream. Attempting to use a write() method on FileInputStream incorrectly reflects a misunderstanding of Java's I/O stream architecture, leading to syntax and functionality errors during compilation .

You might also like