gpt4 book ai didi

java - 更新 eclipse 插件中的 IFile 内容

转载 作者:行者123 更新时间:2023-12-01 18:04:32 26 4
gpt4 key购买 nike

我有一个文件,我想根据某些用户菜单选择来更新该文件。我的代码获取 IFile如果它不存在,则已创建(使用用户的内容),如果存在,则应更新。我当前的代码是:

    String userString= "original String"; //This will be set by the user
byte[] bytes = userString.getBytes();
InputStream source = new ByteArrayInputStream(bytes);
try {
if( !file.exists()){
file.create(source, IResource.NONE, null);
}
else{
InputStream content = file.getContents();
//TODO augment content
file.setContents(content, 1, null);
}

} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

try {
IDE.openEditor(page, file);

我的问题是,即使我获取了原始内容并设置了文件的内容,但在更新时我得到了一个空文件,即整个内容都被删除了。

我做错了什么?

最佳答案

您评论中的这个版本的代码对我有用:

InputStream inputStream = file.getContents();

StringWriter writer = new StringWriter();

// Copy to string, use the file's encoding
IOUtils.copy(inputStream, writer, file.getCharset());

// Done with input
inputStream.close();

String theString = writer.toString();

theString = theString + " added";

// Get bytes using the file's encoding
byte[] bytes = theString.getBytes(file.getCharset());

InputStream source = new ByteArrayInputStream(bytes);

file.setContents(source, IResource.FORCE, null);

注意原始输入流的关闭以及使用 file.getCharset() 来使用正确的编码。

关于java - 更新 eclipse 插件中的 IFile 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37756225/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com