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

File Handling

This document demonstrates how to handle files in Java. It shows how to write content to a file using a BufferedWriter and how to read the content of a file using a BufferedReader. The main method writes the string "This is a file handling example." to a Test.txt file and then reads and prints the content. The writeToFile and readFromFile methods handle writing content to and reading content from files, catching any IOExceptions.
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)
17 views2 pages

File Handling

This document demonstrates how to handle files in Java. It shows how to write content to a file using a BufferedWriter and how to read the content of a file using a BufferedReader. The main method writes the string "This is a file handling example." to a Test.txt file and then reads and prints the content. The writeToFile and readFromFile methods handle writing content to and reading content from files, catching any IOExceptions.
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
You are on page 1/ 2

FILE HANDLING

package FileHandling;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOExcepƟon;
import java.io.File;
public class FileHandling {
public staƟc void main(String[] args) {
String filePath = "Test.txt";
writeToFile(filePath, "This is a file handling example.");
String content = readFromFile(filePath);
System.out.println("Content read from file:\n" + content);
}
private staƟc void writeToFile(String filePath, String content) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
writer.write(content);
System.out.println("the file is wriƩen by some content");
} catch (IOExcepƟon e) {
e.printStackTrace();
}
}
private staƟc String readFromFile(String filePath) {
StringBuilder content = new StringBuilder();
File file = new File(filePath);
if (file.exists()) {
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
} catch (IOExcepƟon e) {
e.printStackTrace();
}
} else {
System.out.println("The file does not exist.");
}
return content.toString();
}
}

You might also like