覆盖通过FileDescriptor FD获得的FileOutputStream中的属性文件 [英] Overwrite a properties file from the FileOutputStream obtained through FileDescriptor FD
问题描述
特殊的问题是
当我将properties.store
代码与从文件路径获得的FileOutputStream
一起使用时,以上方法都可以正常工作,但是当我从从FileDescriptor
获得的FileOutputStream
执行此操作时,将属性文件附加到该文件中,则不会覆盖
Peculiar problem is
When I am using the properties.store
code with the FileOutputStream
obtained from file path, the above method works all fine but when I do that from FileOutputStream
obtained from FileDescriptor
the properties file append to it, doesn't overwrite.
由于我正在使用FileLock,并且现在无法再次通过文件获取FileOutputStream,所以现在的约束是使用后一种方法.
Now my constraint is to use the later approach since I am using FileLock and cant get the FileOutputStream through file again.
- 有可能吗?使用后面的方法做些事情并覆盖和
- 如果没有,我有什么选择?
这两段代码是
第一种方法
OutputStream out = null;
try {
if (portFile != null && portFile.exists()) {
out = new FileOutputStream(portFile);
} else {
try {
portFile.createNewFile();
} catch (IOException e) {
LOGGER.error("error in creating properties file ", e);
}
out = new FileOutputStream(portFile);
}
} catch (FileNotFoundException e) {
LOGGER.error("Not able to get outputstream on properties file ", e);
}
try {
properties.store(out, CJDPluginConstants.PROP_NAME_PORT_MIN);
} catch (IOException e) {
LOGGER.error("Not able to save properties file ", e);
}
第二种方法
// so we move to raf now
OutputStream out = null;
if (portFileRandomAccess != null && channel != null) {
//ByteBuffer buffer = ByteBuffer.allocate(1024);
try {
if (buffer != null) {
//if (buffer != null) {
buffer.flip();
LOGGER.info("buffer what we get we are writing ? " + buffer.asCharBuffer());
out = new ByteBufferBackedOutputStream(buffer);
FileOutputStream fos = new FileOutputStream(portFileRandomAccess.getFD());
//fos.flush();
properties.store(fos, CJDPluginConstants.PROP_NAME_PORT_MIN);
buffer.clear();
buffer = null;
//}
}
} catch (IOException e) {
LOGGER.error("Not able to save properties file ", e);
}
}
//release lock, close channel
if (lock != null) {
try {
lock.release();
} catch (IOException e) {
LOGGER.error("Error releasing lock", e);
}
}
if (channel != null) {
try {
channel.close();
} catch (IOException e) {
LOGGER.error("Error closing channel", e);
}
}
推荐答案
如果您有FileOutputStream
,则无论创建方式如何,都很容易将关联文件的长度截断为零:
If you have a FileOutputStream
, regardless of how you created it, it’s easy to truncate the associated file to a zero length:
fileOutputStream.getChannel().truncate(0);
然后文件为空,然后向其中写入新内容.
Then the file is empty and you write new contents to it.
还可以进行真正的覆盖,即将旧内容保留在您未写入的区域:
It’s also possible to do a real overwrite, i.e. keeping old contents at regions you don’t write to:
fileOutputStream.getChannel().position(0);
然后,下一次写入将移至指定位置,覆盖与实际写入一样多的字节,但保留所有其他字节.
Then the next writes go to the specified position overwriting as much bytes as you really write, but retaining all other bytes.
这篇关于覆盖通过FileDescriptor FD获得的FileOutputStream中的属性文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!