10 useful java file read and write. code.
10 Useful Java Programs for File Read & Write:
Here are 10 examples of Java programs demonstrating useful file read and write functionalities.
1. Simple File Writer:
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterExample {
public static void main(String[] args) {
try (FileWriter writer = new FileWriter("output.txt")) {
writer.write("This is a sample text file.");
writer.flush();
System.out.println("File written successfully!");
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
}
}
}
Description: This program writes a simple string to a text file named "output.txt".
2. File Reader:
import java.io.FileReader;
import java.io.IOException;
public class FileReaderExample {
public static void main(String[] args) {
try (FileReader reader = new FileReader("input.txt")) {
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
}
}
Description: This program reads a text file named "input.txt" character by character and prints it to the console.
3. File Appender:
import java.io.FileWriter;
import java.io.IOException;
public class FileAppender {
public static void main(String[] args) {
try (FileWriter writer = new FileWriter("output.txt", true)) { // true for append
writer.write("\nThis line will be appended.");
writer.flush();
System.out.println("File appended successfully!");
} catch (IOException e) {
System.err.println("Error appending to file: " + e.getMessage());
}
}
}
Description: This program appends a new line to the existing "output.txt" file.
4. CSV Reader:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class CSVReaderExample {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("data.csv"))) {
String line;
while ((line = reader.readLine()) != null) {
String[] values = line.split(",");
System.out.println("Name: " + values[0] + ", Age: " + values[1]);
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
}
}
Description: This program reads a CSV file ("data.csv") and splits each line based on the comma delimiter, displaying name and age.
5. Text File Line Counter:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class LineCounterExample {
public static void main(String[] args) {
int lineCount = 0;
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
lineCount++;
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
System.out.println("Total lines: " + lineCount);
}
}
Description: This program counts the number of lines in a text file.
6. File Copier:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopier {
public static void main(String[] args) {
try (FileInputStream in = new FileInputStream("source.txt");
FileOutputStream out = new FileOutputStream("copy.txt")) {
int byteRead;
while ((byteRead = in.read()) != -1) {
out.write(byteRead);
}
System.out.println("File copied successfully!");
} catch (IOException e) {
System.err.println("Error copying file: " + e.getMessage());
}
}
}
Description: This program copies the content of a source file ("source.txt") to a destination file ("copy.txt").
7. Word Counter:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class WordCounterExample {
public static void main(String[] args) {
int wordCount = 0;
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
String[] words = line.split("\\s+");
wordCount += words.length;
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
System.out.println("Total words: " + wordCount);
}
}
Description: This program counts the number of words in a text file.
8. File Renamer:
import java.io.File;
import java.io.IOException;
public class FileRenamer {
public static void main(String[] args) {
File file = new File("old_name.txt");
if (file.exists() && file.isFile()) {
if (file.renameTo(new File("new_name.txt"))) {
System.out.println("File renamed successfully!");
} else {
System.err.println("Error renaming file.");
}
} else {
System.err.println("File does not exist.");
}
}
}
Description: This program renames a file from "old_name.txt" to "new_name.txt".
9. File Deleter:
import java.io.File;
import java.io.IOException;
public class FileDeleter {
public static void main(String[] args) {
File file = new File("temp.txt");
if (file.exists() && file.isFile()) {
if (file.delete()) {
System.out.println("File deleted successfully!");
} else {
System.err.println("Error deleting file.");
}
} else {
System.err.println("File does not exist.");
}
}
}
Description: This program deletes a file named "temp.txt".
10. File Encryption & Decryption:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.Key;
import java.util.Base64;
public class FileEncryption {
private static final String SECRET_KEY = "your_secret_key";
private static final String ALGORITHM = "AES";
public static void encryptFile(String inputFile, String outputFile) throws Exception {
Key key = generateKey();
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
try (FileInputStream in = new FileInputStream(inputFile);
FileOutputStream out = new FileOutputStream(outputFile)) {
byte[] inputBytes = new byte[64];
int bytesRead;
while ((bytesRead = in.read(inputBytes)) != -1) {
byte[] encryptedBytes = cipher.update(inputBytes, 0, bytesRead);
if (encryptedBytes != null) {
out.write(encryptedBytes);
}
}
out.write(cipher.doFinal());
}
}
public static void decryptFile(String inputFile, String outputFile) throws Exception {
Key key = generateKey();
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
try (FileInputStream in = new FileInputStream(inputFile);
FileOutputStream out = new FileOutputStream(outputFile)) {
byte[] inputBytes = new byte[64];
int bytesRead;
while ((bytesRead = in.read(inputBytes)) != -1) {
byte[] decryptedBytes = cipher.update(inputBytes, 0, bytesRead);
if (decryptedBytes != null) {
out.write(decryptedBytes);
}
}
out.write(cipher.doFinal());
}
}
private static Key generateKey() throws Exception {
byte[] encodedKey = Base64.getDecoder().decode(SECRET_KEY);
return new SecretKeySpec(encodedKey, ALGORITHM);
}
public static void main(String[] args) throws Exception {
encryptFile("input.txt", "encrypted.txt");
decryptFile("encrypted.txt", "decrypted.txt");
}
}