Inserting text into an existing file via Java
Okay, this question is pretty old, but FileChannels exist since Java 1.4 and I don't know why they aren't mentioned anywhere when dealing with the problem of replacing or inserting content in files. FileChannels are fast, use them.
Here's an example (ignoring exceptions and some other stuff):
public void insert(String filename, long offset, byte[] content) {
RandomAccessFile r = new RandomAccessFile(new File(filename), "rw");
RandomAccessFile rtemp = new RandomAccessFile(new File(filename + "~"), "rw");
long fileSize = r.length();
FileChannel sourceChannel = r.getChannel();
FileChannel targetChannel = rtemp.getChannel();
sourceChannel.transferTo(offset, (fileSize - offset), targetChannel);
sourceChannel.truncate(offset);
r.seek(offset);
r.write(content);
long newOffset = r.getFilePointer();
targetChannel.position(0L);
sourceChannel.transferFrom(targetChannel, newOffset, (fileSize - offset));
sourceChannel.close();
targetChannel.close();
}
How to append text to an existing file in Java?
Are you doing this for logging purposes? If so there are several libraries for this. Two of the most popular are Log4j and Logback.
Java 7+
For a one-time task, the Files class makes this easy:
try {
Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
Careful: The above approach will throw a NoSuchFileException
if the file does not already exist. It also does not append a newline automatically (which you often want when appending to a text file). Another approach is to pass both CREATE
and APPEND
options, which will create the file first if it doesn't already exist:
private void write(final String s) throws IOException {
Files.writeString(
Path.of(System.getProperty("java.io.tmpdir"), "filename.txt"),
s + System.lineSeparator(),
CREATE, APPEND
);
}
However, if you will be writing to the same file many times, the above snippets must open and close the file on the disk many times, which is a slow operation. In this case, a BufferedWriter
is faster:
try(FileWriter fw = new FileWriter("myfile.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println("the text");
//more code
out.println("more text");
//more code
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
Notes:
- The second parameter to the
FileWriter
constructor will tell it to append to the file, rather than writing a new file. (If the file does not exist, it will be created.) - Using a
BufferedWriter
is recommended for an expensive writer (such asFileWriter
). - Using a
PrintWriter
gives you access toprintln
syntax that you're probably used to fromSystem.out
. - But the
BufferedWriter
andPrintWriter
wrappers are not strictly necessary.
Older Java
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
Exception Handling
If you need robust exception handling for older Java, it gets very verbose:
FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
try {
fw = new FileWriter("myfile.txt", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
finally {
try {
if(out != null)
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(fw != null)
fw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
}
How to add a new line of text to an existing file in Java?
you have to open the file in append mode, which can be achieved by using the FileWriter(String fileName, boolean append)
constructor.
output = new BufferedWriter(new FileWriter(my_file_name, true));
should do the trick
Java add text to a specific line in a file
In Java 7+ you can use the Files
and Path
class as following:
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
lines.add(position, extraLine);
Files.write(path, lines, StandardCharsets.UTF_8);
To give an example:
Path path = Paths.get("C:\\Users\\foo\\Downloads\\test.txt");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
int position = lines.size() / 2;
String extraLine = "This is an extraline";
lines.add(position, extraLine);
Files.write(path, lines, StandardCharsets.UTF_8);
How to insert text after a particular line of a file
There's no way to insert text in the middle of a file because of how file systems work. They implement operations to modify the data blocks of a file and to add and remove blocks from the end of a file. What they don't implement is adding or removing data blocks anywhere else because of inherent complexities of these operations.
What you have to do is copy the first 125 lines to a new file, add what you want to add, and then copy the rest of the file. If you want to you can then rename the new file as the old file so you don't accumulate temporary files.
inserting data in the middle of a text file through java
You have to read your file and rewrite it. During this operation you have to find the place where you want to put your text and write it.
Related Topics
Selenium Ie Webdriver Only Works While Debugging
How to Have a Jtabbedpane with a Jmenubar
How to Make Image Appear Randomly Every X Seconds in Java Using Timer
Swingworker, Thread.Sleep(), or Javax.Swing.Timer? I Need to "Insert a Pause"
What Goes into the "Controller" in "Mvc"
Updating Version Numbers of Modules in a Multi-Module Maven Project
Using Enum Values as String Literals
Intellij Show Javadocs Tooltip on Mouse Over
Is Null Check Needed Before Calling Instanceof
How to Initialize Hashset Values by Construction
Difference Between Arrays.Aslist(Array) and New Arraylist<Integer>(Arrays.Aslist(Array))
How to Manage Rest API Versioning with Spring
Spring: Why Do We Autowire the Interface and Not the Implemented Class
A For-Loop to Iterate Over an Enum in Java
Can You Explain the Httpurlconnection Connection Process
Spring Resttemplate Get with Parameters