可能重複:
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();
任何幫助將不勝感激,在此先感謝。
在文件中你可以覆蓋數據,你可以在最後附加數據。如果要在中間添加線條,則必須至少將必須手動移動到稍後位置的部分進行復制。 - >除了提高創建副本的速度之外,還可以做更多的事情來提高效率 – zapl