特殊的问题是
当我将 properties.store
代码与从文件路径获取的 FileOutputStream
一起使用时,上述方法工作正常,但是当我从 FileOutputStream
执行此操作时> 从 FileDescriptor
获取属性文件附加到它,不会覆盖。
现在我的限制是使用后面的方法,因为我正在使用 FileLock 并且无法再次通过文件获取 FileOutputStream。
- 这可能吗?用后面的方法做一些事情并覆盖和
- 如果不是,我有什么选择?
这两段代码是
第一种方法
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
,无论您如何创建它,都可以轻松地将关联文件截断为零长度:
fileOutputStream.getChannel().truncate(0);
然后该文件为空,您可以向其中写入新内容。
也可以进行真正的覆盖,即将旧内容保留在您不写入的区域:
fileOutputStream.getChannel().position(0);
然后下一次写入将转到指定位置,覆盖实际写入的字节数,但保留所有其他字节。
关于java - 覆盖通过 FileDescriptor FD 获取的 FileOutputStream 中的属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20394276/