From your description it sounds like you're writing to an existing file and want to enhance it's content and that you're not creating it from scratch.
I'm not sure if it'll be possible to directly write the new line to a specific place of that file, but as a "quick workaround" you can simply copy the old file to a tmp file and during this copy process arrange the lines like you like. At the end of the process you'll remove the original file and replace it with the tmp file.
It'll look like you've simply enhanced the previous one with your new lines.
Actually the following example gets along without a temp file and works by directly replacing the original 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);
The full example might look like:
enum InsertPosition {
BEFORE, AFTER;
}
public static void main(String[] args) throws IOException {
Path path = Paths.get("C:\\Users\\foo\\Downloads\\Test.txt");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
int position = findPosition(lines, "see", InsertPosition.AFTER);
String extraLine = "so";
lines.add(position, extraLine); // Note -1 can be returned from "findPosition" which will lead to an exception here, but you can simply suround it with an additional if
Files.write(path, lines, StandardCharsets.UTF_8);
}
private static int findPosition(List<String> lines, String lineToLookFor, InsertPosition position) {
for (int i = 0; i < lines.size(); i++) {
if (lineToLookFor.equals(lines.get(i))) {
if (position == InsertPosition.BEFORE) {
return i;
} else if (position == InsertPosition.AFTER) {
return i + 1;
}
}
}
return -1;
}
When the original file looks like this:
1
see
3
The output will be:
1
see
so
3
With this solution be aware that it might consume quite much memory since the whole content of the file will be buffered in memory while it's being processed. This means it can be neglected on small files, but might perform bad on bigger ones.
In case you want and need to process bigger files as well you can implement a more stream like approach, in which only several lines of a huge file will be buffered in memory.