在文件中间写入java的最佳方法
可能重复:在文件中间写入java的最佳方法,java,io,postscript,Java,Io,Postscript,可能重复: 我正在编写一个修改PASScript文件以添加打印属性的程序,所以我需要在文件中间添加行。这些PostScript文件非常大,我想知道我使用的代码是否最有效。这段代码读取源文件并编写一个临时文件,在需要的地方添加一行 Writer out = null; Scanner scanner = null; String newLine = System.getProperty("line.separator"); scanner = new Scan
<>我正在编写一个修改PASScript文件以添加打印属性的程序,所以我需要在文件中间添加行。这些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();
Writer out=null;
扫描器=空;
字符串newLine=System.getProperty(“line.separator”);
scanner=newscanner(newfileinputstream(fileToRead));
out=新的OutputStreamWriter(新的FileOutputStream(fileToWrite));
弦线;
while(scanner.hasNextLine()){
line=scanner.nextLine();
写出(行);
out.write(换行符);
如果(行等于(“%%BeginSetup”)){
out.write(“>setpagedevice”);
out.write(换行符);
}
}
scanner.close();
out.close();
感谢您的帮助。请参阅
RandomAccessFile
及其示例:-您可以查找文件中的特定位置并将其写入其中。在SO上找到的大多数旧答案都使用/链接旧的java.io.
Oracle提供了一些很好的示例,说明如何使用“新”Java7java.nio.*
包(通常性能更好)来实现这一点
在文件中,您可以覆盖数据,也可以在结尾追加数据。如果要在中间添加行,则必须手动复制至少要移动到稍后位置的部分。->除了提高创建副本的速度之外,要使其更高效,您所能做的不多