Let’s say c:/myFile.txt looks like this >
you learning file io from javaMadeSoEasy
|
Write a Program to insert/write content at specific position in file in java, such that after execution of program file must look like this -
you ARE learning file io from javaMadeSoEasy
|
Java does not allow you to insert in file, so follow these steps >
- 1) Read from file in String.
- 2) Insert content at specified position in String, as per your requirement.
- 3) write updated String in file.
RandomAccessFile allows us to read/write at random positions by using seek method but when we try to write at random position, data is not inserted, in fact it’s overridden. See How to Read/write from file using RandomAccessFile.
Program to insert/write content at specific position in file in java >
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class InsertInFileAtSpecifiedPosition {
public static void main(String[] args) throws IOException {
String fileName = "c:/myFile.txt";
FileReader fr = new FileReader("c:/myFile.txt");
BufferedReader br = new BufferedReader(fr);
// 1) Read from file in String
String str = br.readLine();
// 2) Insert content at specified position in String, as per your
// requirement
String updatedStr = str.substring(0, 4) + "ARE " + str.substring(4);
br.close();
// 3) write updated String in file
FileWriter writer = new FileWriter(fileName);
writer.write(updatedStr);
writer.close();
}
}
|
After executing above program c:/myFile.txt will look like this >
you ARE learning file io from javaMadeSoEasy
|
RELATED LINKS>
Create File using createNewFile() method in java file IO
Copy a file in java 2 in ways
Find current directory or current path in java
Labels:
Core Java
File IO/File handling