Published by: Dikshya
Published date: 02 Jul 2023
Random-Access Files:
Example:
import java.io.RandomAccessFile;
public class RandomAccessFileExample {
public static void main(String[] args) {
try {
RandomAccessFile file = new RandomAccessFile("data.txt", "rw");
// Writing data to the file
file.writeUTF("Hello");
file.writeInt(123);
file.writeDouble(3.14);
// Moving the file pointer to a specific location
file.seek(0);
// Reading data from the file
String text = file.readUTF();
int number = file.readInt();
double value = file.readDouble();
System.out.println("Text: " + text);
System.out.println("Number: " + number);
System.out.println("Value: " + value);
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
In this example, we create a RandomAccessFile object named file
and open it in "rw" mode (read and write). We then write some data to the file using various methods like writeUTF
, writeInt
, and writeDouble
. After that, we move the file pointer to the beginning of the file using seek
method. Finally, we read the data back from the file using methods like readUTF
, readInt
, and readDouble
, and display the values on the console.
Files and Directories:
Creating a Directory
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateDirectoryExample {
public static void main(String[] args) {
try {
Path directoryPath = Paths.get("mydir");
Files.createDirectory(directoryPath);
System.out.println("Directory created successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
This example creates a new directory named "mydir" using the createDirectory
method from the Files
class.
Creating a File:
import java.io.File;
import java.io.IOException;
public class CreateFileExample {
public static void main(String[] args) {
try {
File file = new File("myfile.txt");
if (file.createNewFile()) {
System.out.println("File created successfully.");
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example, we create a new file named "myfile.txt" using the createNewFile
method from the File
class. It returns true
if the file is created successfully, or false
if the file already exists.