【问题标题】:Best way in Java to write in the middle of a file [duplicate]Java中在文件中间写入的最佳方法[重复]
【发布时间】:2012-11-29 01:21:39
【问题描述】:

可能重复:
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();

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

【问题讨论】:

  • 在文件中你可以覆盖数据,你可以在最后追加数据。如果要在中间添加线条,则必须至少复制必须手动移动到稍后位置的部分。 -> 除了提高创建副本的速度之外,您无能为力提高效率

标签: java io postscript


【解决方案1】:

在 SO 上找到的大多数旧答案都使用/链接旧的 java.io.*

Oracle 有很好的示例如何使用“新”java 7 java.nio.* 包(通常具有更好的性能)来做到这一点

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2010-09-15
      • 2011-03-19
      • 1970-01-01
      • 2021-09-08
      • 2014-09-05
      • 2013-10-21
      • 2013-05-24
      • 1970-01-01
      相关资源
      最近更新 更多