A.Anbumani, P23CS369
import java.io.*;
import java.nio.file.*;
import java.util.List;
import java.util.stream.Collectors;
public class AFO{
// Read file content
public static void readFile(String filePath) throws IOException {
List<String> lines = Files.readAllLines(Paths.get(filePath));
for (String line : lines) {
System.out.println(line);
}
}
// Write content to a file
public static void writeFile(String filePath, String content) throws IOException {
Files.write(Paths.get(filePath), content.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
}
// Copy a file
public static void copyFile(String sourcePath, String destinationPath) throws IOException {
Files.copy(Paths.get(sourcePath), Paths.get(destinationPath), StandardCopyOption.REPLACE_EXISTING);
}
// Move a file
public static void moveFile(String sourcePath, String destinationPath) throws IOException {
Files.move(Paths.get(sourcePath), Paths.get(destinationPath), StandardCopyOption.REPLACE_EXISTING);
}
// Delete a file
public static void deleteFile(String filePath) throws IOException {
Files.delete(Paths.get(filePath));
}
// List all files in a directory
public static void listFiles(String directoryPath) throws IOException {
List<Path> files = Files.list(Paths.get(directoryPath)).collect(Collectors.toList());
for (Path file : files) {
System.out.println(file.getFileName());
}
}
public static void main(String[] args) {
try {
// Specify file paths
String filePath = "example.txt";
String copyPath = "example_copy.txt";
String movePath = "example_moved.txt";
String directoryPath = ".";
// Write content to a file
writeFile(filePath, "Hello, world!\n");
// Read file content
System.out.println("File content:");
readFile(filePath);
// Copy the file
copyFile(filePath, copyPath);
System.out.println("File copied to " + copyPath);
// Move the file
moveFile(copyPath, movePath);
System.out.println("File moved to " + movePath);
// List all files in the current directory
System.out.println("Files in the current directory:");
listFiles(directoryPath);
// Delete the original and moved files
deleteFile(filePath);
deleteFile(movePath);
System.out.println("Files deleted");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output of the File operation. program
Comments
Post a Comment