0% found this document useful (0 votes)
31 views8 pages

Java File I/O Operations and Examples

The document contains 9 Java programs that demonstrate various file input/output operations in Java like reading/writing to files, copying files, using buffered readers/writers. Program 1 reads data from a file into a byte array and prints it. Program 2 writes bytes to a file and reads them back printing the characters. The other programs demonstrate additional file I/O operations like writing strings to files, copying files, reading/writing using FileReader/FileWriter and BufferedReader.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views8 pages

Java File I/O Operations and Examples

The document contains 9 Java programs that demonstrate various file input/output operations in Java like reading/writing to files, copying files, using buffered readers/writers. Program 1 reads data from a file into a byte array and prints it. Program 2 writes bytes to a file and reads them back printing the characters. The other programs demonstrate additional file I/O operations like writing strings to files, copying files, reading/writing using FileReader/FileWriter and BufferedReader.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Program#1

import [Link];
import [Link];

class Main {
public static void main(String args[]) {

byte[] array = new byte[100];

try {
FileInputStream input = new FileInputStream("[Link]");

[Link]("Available bytes in the file: " +


[Link]());

// Read byte from the input stream


[Link](array);
[Link]("Data read from the file: ");

// Convert byte array into string


String data = new String(array);
[Link](data);

// Close the input stream


[Link]();
} catch (Exception e) {
[Link]();
}
}
}
Program#2
import [Link].*;
public class fileStreamTest{
public static void main(String args[]){
try{
byte b [] = {11,21,3,40,5};
FileOutputStream os = new FileOutputStream("[Link]");
for(int x=0; x < [Link] ; x++){
[Link]( b [x] ); // writes the bytes
}
[Link]();
InputStream is = new FileInputStream("[Link]");
int size = [Link]();
for(int i=0; i< size; i++){
[Link]((char)[Link]() + " ");
}
[Link]();
}catch(IOException e){
[Link]("Exception");
}
}
}
Program #3
import [Link];
import [Link];

public class Main {

public static void main(String args[]) {


String data = "This is a line of text inside the file.";

try {
OutputStream out = new FileOutputStream("[Link]");

// Converts the string into bytes


byte[] dataBytes = [Link]();

// Writes data to the output stream


[Link](dataBytes);
[Link]("Data is written to the file.");

// Closes the output stream


[Link]();
}

catch (Exception e) {
[Link]();
}
}
}
Program # 4
import [Link].*;
public class CopyFile {

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


FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("[Link]");
out = new FileOutputStream("[Link]");

int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
}finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}
Program # 5

import [Link];
import [Link];

public class abc {

public static void main(String[] args) {

// Creating file object and specifying path


File file = new File("[Link]");

try {
FileInputStream input= new FileInputStream(file);
int character;
while ([Link]()!=0) {
character = [Link]();
[Link]((char)character);
}

[Link]();
}

catch (Exception e) {

[Link]();
}
}
}

Program#6
import [Link];
import [Link];
class CreateFile
{
public static void main(String[] args) throws IOException
{
String str = "File Handling in Java using "+
FileWriter fw=new FileWriter("[Link]");
for (int i = 0; i < [Link](); i++)
[Link]([Link](i));
[Link]("Writing successful");
[Link]();
}
}
Program #7
import [Link];
import [Link];
import [Link];
class ReadFile
{
public static void main(String[] args) throws IOException
{
int ch;

FileReader fr=null;
try
{
fr = new FileReader("[Link]");
}
catch (FileNotFoundException fe)
{
[Link]("File not found");
}

while ((ch=[Link]())!=-1)
[Link]((char)ch);

[Link]();
}
}
Program#8
import [Link].*;
public class CopyFile {

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


FileReader in = null;
FileWriter out = null;

try {
in = new FileReader("[Link]");
out = new FileWriter("[Link]");

int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
}finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}

Program#9

import [Link].*;
public class BufferedReaderExample{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader([Link]);
BufferedReader br=new BufferedReader(r);
[Link]("Enter your name");
String name=[Link]();
[Link]("Welcome "+name);
}
}
import [Link].*;
public class GFG {
public static void main(String[] args)
{

FileReader fileReader = new FileReader("c:/[Link]");


BufferedReader buffReader = new BufferedReader(fileReader);
while ([Link]()) {
[Link](
[Link]());
}
}
}

Common questions

Powered by AI

FileOutputStream manages byte streams and is useful for writing binary data, while FileWriter handles character streams, suitable for writing text data. In Program #2, FileOutputStream is used to write byte arrays to a file, showing suitability for non-text content, whereas FileWriter in Program #6 writes character data from a string, catering to text-based file operations.

File copying programs exemplify best practices by using structured read and write loops, handling exceptions, and ensuring resource closure. These patterns maximize performance and reliability by preventing data corruption, resource leaks, and encapsulating operations in try-finally blocks. They demonstrate how a robust design contributes to maintainable and efficient code, adaptable across various I/O scenarios.

Failing to close an InputStream can lead to resource leaks, memory consumption, and potential application crashes. Properly closing the InputStream, as demonstrated in structured try-finally blocks and try-with-resources, ensures efficient resource management and application stability, preventing performance degradation and system resource exhaustion over time.

FileOutputStream directly handles byte streams, preserving the original binary format, crucial for non-text files like images or executables. Character-based streams, such as those used in character-to-byte conversion, could potentially alter bytes due to character encoding, leading to data corruption. Programs handling byte-specific operations, such as Program #4, should use FileOutputStream to maintain data integrity.

The try-with-resources statement automatically closes resources once the program finishes the try block, which simplifies the code and ensures that resources are always closed in case of an exception. It contrasts with the traditional try-finally structure, where each resource must be explicitly closed, potentially leading to more complex and error-prone code.

FileInputStream is used for reading raw byte streams such as image data, while FileReader is used for reading character streams, which is suitable for text files. Consequently, FileInputStream should be preferred when handling binary files or non-text data, and FileReader should be used for processing text files to take advantage of character encoding.

BufferedReader buffers the input, which reduces the number of I/O operations by reading larger chunks of data at once. This buffering mechanism results in more efficient data processing when compared to using FileReader or InputStreamReader directly, which read character by character, causing performance bottlenecks, especially with large data sets.

Using OutputStream's write method with a byte array allows for flexible data handling, enabling the conversion and writing of various data types (e.g., strings) in a consistent binary format. This approach facilitates diverse I/O operations and enhances program robustness by manipulating raw data efficiently.

Checking file existence before operations is essential for robust applications to avoid runtime errors. By catching FileNotFoundException in Program #7, the code preempts and handles potential errors gracefully, which enhances stability and provides user feedback rather than allowing the application to crash unexpectedly, demonstrating good coding practice.

Utilizing catch blocks that print stack traces aids in error diagnosis by providing insight into the exception's source and context. This practice supports developers in debugging and enhancing code reliability by identifying and addressing potential issues, thus improving the user experience by avoiding uncontrolled failures.

You might also like