- Common file operations include:
- Opening: creates a connection between the file and the program
- Reading: retrieves data from a file
- Writing: saves new data to a file, overwriting existing content
- Appending: adds new data to the end of a file without overwriting existing content
- Closing: ends the connection between the file and the program, releasing system resources
- Single items of data can be numbers, characters, or other simple data types
- A line of text typically ends with a newline character or an end-of-line marker
Pseudocode example:
OPEN "file.txt"
filedata = READ data
PRINT filedata
CLOSE file
OPEN "file.txt"
WRITE data
CLOSE file
Python example:
with open("file.txt", "r") as file:
data = file.read()
print(data)
with open("file.txt", "w") as file:
file.write(data)
Java example:
public static void main(String[] args) {
String path = ("file.txt");
try {
FileReader f = new FileReader(path);
BufferedReader reader = new BufferedReader(f);
String data = reader.readLine();
reader.close();
BufferedWriter out = new BufferedWriter(f);
out.write(data);
out.close();
} catch (Exception e) {
System.err.println("No file found");
}
}
Visual Basic example:
Dim File As New System.IO.StreamReader("file.txt")
Console.WriteLine(File.ReadLine())
File.Close()
Dim fileWrite As New System.IO.StreamWriter("file.txt")
fileWrite.WriteLine(data)
fileWrite.Close()