This includes support for common operations like creating, reading from and writing to files; copy-pasting content between them; appending new information or deleting it completely - making these an ideal choice when dealing with complex file system tasks.
The most important classes for working with files in Java are
- File: This class represents a file or directory on the file system. You can use it to perform operations such as creating, deleting, and renaming files.
- FileReader and FileWriter: These classes provide a way to read and write text data to a file.
- InputStream and OutputStream: These classes provide a way to read and write binary data to a file.
The following code creates a new file called "example.txt" and writes the text "Hello, World!" to it:
File file = new File("example.txt");
FileWriter writer = new FileWriter(file);
writer.write("Hello, World!");
writer.close();
Similarly, the following code reads the text from the file "example.txt" and prints it to the console:
FileReader reader = new FileReader(file);
int c;
while((c = reader. read()) != -1) {
System.out.print((char)c);
}
reader.close();
It will print "Hello, World!"