簡體   English   中英

在eclipse插件中更新IFile內容

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM