File handling is a common task in programming, and Java makes it straightforward with built-in libraries. Below are two useful functions for reading and writing files, along with descriptions of how to use them. Ensure you import java.io for these functions to work properly.
The readFile function reads the entire contents of a file and returns it as a single string. To use it, pass the file path as a string to the function.
static String readFile(String myFile){
String returnValue="";
try(BufferedReader br = new BufferedReader(new FileReader(myFile))) {
for(String line; (line = br.readLine()) != null; ) {
returnValue = returnValue + line + "\r\n";
}
}
catch(Exception e){}
return returnValue;
}
Usage:
readFile.The writeFile function writes a string to a specified file path. If the file already exists, its contents will be overwritten.
static void writeFile(String myString, String myPath){
try{
PrintWriter writer = new PrintWriter(myPath, "UTF-8");
writer.print(myString);
writer.close();
}
catch(Exception e){}
}
Usage:
writeFile.readFile, exceptions are caught silently, so validate the file path before use.writeFile function uses UTF-8 encoding, ensuring compatibility with most text files.Here’s an example demonstrating how to use these functions:
public class FileHandlingExample {
public static void main(String[] args) {
String filePath = "example.txt";
String content = "Hello, World!\nThis is a test file.";
// Writing to a file
writeFile(content, filePath);
// Reading from a file
String fileContents = readFile(filePath);
System.out.println("File Contents:\n" + fileContents);
}
static String readFile(String myFile){
String returnValue="";
try(BufferedReader br = new BufferedReader(new FileReader(myFile))) {
for(String line; (line = br.readLine()) != null; ) {
returnValue = returnValue + line + "\r\n";
}
}
catch(Exception e){}
return returnValue;
}
static void writeFile(String myString, String myPath){
try{
PrintWriter writer = new PrintWriter(myPath, "UTF-8");
writer.print(myString);
writer.close();
}
catch(Exception e){}
}
}
This example writes content to a file and then reads it back to display on the console. By leveraging these simple functions, you can easily handle file I/O operations in your Java applications.