简体   繁体   English

在eclipse插件中更新IFile内容

[英]update IFile content in eclipse plugin

I have a File that I would like to update based on some user menu selection. 我有一个要根据某些用户菜单选择更新的文件。 My code gets the IFile if it does not exist it's been created (with the user's content),and if it exists it should be updated. 如果代码不存在(使用用户的内容创建),我的代码将获取IFile,如果存在,则应对其进行更新。 My current code is: 我当前的代码是:

    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);

My problem is that even though I get the original content and set the file's content, I am getting an empty file upon update , ie, the entire content is being deleted. 我的问题是,即使我获得了原始内容并设置了文件的内容,但在更新时却得到了一个空文件,即整个内容都被删除了。

What am I doing wrong? 我究竟做错了什么?

This version of the code in your comment works for me: 您评论中的此代码版本对我有效:

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);

Note the close of the original input stream and the use of file.getCharset() to use the correct encoding. 请注意原始输入流的关闭以及使用file.getCharset()来使用正确的编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM