2

Possible Duplicate:
Best Way to Write Bytes in the Middle of a File in Java

I'm writing a program that modifies a PostScript file to add print properties, so I need to add lines in the middle of the file. These PostScript files are very large, and I want to know if the code I'm using is the most efficient. This code reads the source file and writes a temporary file adding a line where is needed.

    Writer out = null;
    Scanner scanner = null;

    String newLine = System.getProperty("line.separator");

    scanner = new Scanner(new FileInputStream(fileToRead));
    out = new OutputStreamWriter(new FileOutputStream(fileToWrite));
    String line;
    while(scanner.hasNextLine()){
        line = scanner.nextLine();

        out.write(line);
        out.write(newLine);
        if(line.equals("%%BeginSetup")){
            out.write("<< /Duplex true /Tumble true >> setpagedevice");
            out.write(newLine);
        }
    }

    scanner.close();
    out.close();

Any help will be appreciated, thanks in advance.

Community
  • 1
  • 1
Joel
  • 193
  • 1
  • 6
  • 12
  • In files you can overwrite data and you can append data at the end. If you want to add lines in the middle you have to copy at least the part that has to be moved to a later position manually. -> There is not much you can do to get it more efficient other than improving the speed of creating the copy – zapl Dec 11 '12 at 13:22

2 Answers2

1

Most of the old answers found on SO uses/links the old java.io.*

Oracle has nice examples how to do this using the "new" java 7 java.nio.* packages (usually with much better performance)

http://docs.oracle.com/javase/tutorial/essential/io/rafs.html

Aksel Willgert
  • 11,367
  • 5
  • 53
  • 74
0

See RandomAccessFile and its example here: Fileseek - You can seek to a particular location in the file and write to it there.

Murali
  • 774
  • 6
  • 12
Aniket Inge
  • 25,375
  • 5
  • 50
  • 78