![](/img/trans.png)
[英]How to properly set the content of an IFile in Eclipse plugin when the editor is opened
[英]update IFile content in eclipse plugin
我有一个要根据某些用户菜单选择更新的文件。 如果代码不存在(使用用户的内容创建),我的代码将获取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()
来使用正确的编码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.