简体   繁体   中英

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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