1

Suppose i have a text file named Sample.text. i need advice on how to achieve this:

Sample.txt before running a program: ABCD

while running the program, user will input string to be added starting at the middle for example: user input is XXX

Sample.txt after running a program: ABXXXCD

Aditya
  • 2,876
  • 4
  • 34
  • 30
  • What do you mean by middle and how is `sample.txt` related with this string manipulation? – anubhava Jan 22 '14 at 15:16
  • you can't insert into a file without "moving" the "tail" of the file farther away to make space for the new data. – Marc B Jan 22 '14 at 15:16

4 Answers4

5

Basically you've got to rewrite the file, at least from the middle. This isn't a matter of Java - it's a matter of what file systems support.

Typically the way to do this is to open both the input file and an output file, then:

  • Copy the first part from the input file to the output file
  • Write the middle section to the output file
  • Copy the remainder of the input file to the output file
  • Optionally perform file renaming if you want the new file to have the same eventual name as the original file
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

The basic idea is to read the file contents into memory, say at program start, manipulate the string as desired, then write the entire thing back to the file.

  1. So you would open and read in Sample.txt. In memory you have a string = "ABCD"
  2. in your program execution, accept user input of XXX. Insert that into your string with your favorite string manipulation method. Now string = "ABXXXCD"
  3. Finally you would overwrite Sample.txt with your updated string and close it.

If you were worried about corruption or something, you might save it to a secondary file, then verify its contents, delete the original, and rename the new to be the same as the original.

Vesper
  • 13
  • 3
  • original: ABCD i want it to be like this after running a program: ABXXXCD but what really happened to my code: ABXXX CD was replaced – user3224040 Jan 22 '14 at 23:57
0

Actually i have did something like what you want, here try this code, its not a complete but it should give you a clear idea:

public void addString(String fileContent, String insertData) throws IOException {

        String firstPart = getFirstPart(fileContent);
        Pattern p = Pattern.compile(firstPart);

        Matcher matcher = p.matcher(fileContent);
        int end = 0;
        boolean matched = matcher.find();
        if (matched) {
            end = matcher.end();
        }

        if(matched) {
            String secondPart = fileContent.substring(end);
            StringBuilder newFileContent = new StringBuilder();
            newFileContent.append(firstPart);
            newFileContent.append(insertData);
            newFileContent.append(secondPart);

            writeNewFileContent(newFileContent.toString());
        }
    }
Salah
  • 8,567
  • 3
  • 26
  • 43
0

Normally a new file would be created, but the following probably suffices (for non-gigabyte files). Mind the explicit encoding UTF-8; which you can ommit for the encoding of the operating system.

public static void insertInMidstOfFile(File file, String textToInsert)
        throws IOException {
    if (!file.exists()) {
        throw new FileNotFoundException("File not found: " + file.getPath());
        // Because file open mode "rw" would create it.
    }
    if (textToInsert.isEmpty()) {
        return;
    }
    long fileLength = file.length();
    long startPosition = fileLength / 2;
    long remainingLength = fileLength - startPosition;
    if (remainingLength > Integer.MAX_VALUE) {
        throw new IllegalStateException("File too large");
    }
    byte[] bytesToInsert = textToInsert.getBytes(StandardCharsets.UTF_8);
    try (RandomAccessFile fh = new RandomAccessFile(file, "rw")) {
        fh.seek(startPosition);
        byte[] remainder = new byte[(int)remainingLength];
        fh.readFully(remainder);
        fh.seek(startPosition);
        fh.write(bytesToInsert);
        fh.write(remainder);
    }
}

Java 7 or higher.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138