2012-12-11 36 views
2

可能重复:
Best Way to Write Bytes in the Middle of a File in Java最好的方法在文件中写

我正在写一个修改PostScript文件添加打印性能的程序,所以我需要在文件中间添加行。这些PostScript文件非常大,我想知道我使用的代码是否最有效。这段代码读取源文件并写入一个临时文件,在需要的地方添加一行。

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(); 

任何帮助将不胜感激,在此先感谢。

+0

在文件中你可以覆盖数据,你可以在最后附加数据。如果要在中间添加线条,则必须至少将必须手动移动到稍后位置的部分进行复制。 - >除了提高创建副本的速度之外,还可以做更多的事情来提高效率 – zapl

回答

0

请参阅RandomAccessFile及其示例:Fileseek - 您可以寻找文件中的特定位置并在其中写入。