如果我处理文件,如何创建文档并写入文档?现在,我有完全删除的文件,并用新的内容重新创建,如下图所示:如何在eclipse中写入文件?
IFile file = getFile();
file.delete();
file.create(input, false, null);
编辑:这是一个Eclipse插件,而不是一个普通的Java程序。
如果我处理文件,如何创建文档并写入文档?现在,我有完全删除的文件,并用新的内容重新创建,如下图所示:如何在eclipse中写入文件?
IFile file = getFile();
file.delete();
file.create(input, false, null);
编辑:这是一个Eclipse插件,而不是一个普通的Java程序。
不得不修改了一点,以满足我的需要:
FileEditorInput editorInput = new FileEditorInput(file);
IWorkbench wb = PlatformUI.getWorkbench();
IWorkbenchPage page = wb.getActiveWorkbenchWindow().getActivePage();
IEditorDescriptor desc = wb.getEditorRegistry().getDefaultEditor(file.getName());
IEditorPart editor = (IEditorPart)page.openEditor(editorInput, desc.getId());
ITextEditor textEditor = (ITextEditor) editor.getAdapter(ITextEditor.class);
IDocumentProvider documentProvider = textEditor.getDocumentProvider();
IDocument document = documentProvider.getDocument(editorInput);
document.replace(position, 0, content);
发生这种情况是因为您正尝试读取不存在的文件。因此,通过获取文件并关闭它,然后创建文件。
的IFile接口似乎有一些方法,这样可以让你写一些内容:
/**
* Appends the entire contents of the given stream to this file.
* ...
*/
public void appendContents(InputStream source, boolean force, boolean keepHistory, IProgressMonitor monitor) throws CoreException;
好的答案,但如何在特定位置写入? – fastcodejava 2010-04-19 17:22:28
很好的答案,但如何在特定位置写字? – fastcodejava 2010-04-19 07:14:43
我想“输入”是文件名。所以说我有这个文件在 的C盘(假设你正在运行的窗口)。我还假设“输入”是一个字符串。然后按照以下步骤操作 String n =“C:/”+ input; 该字符串将最终看起来像这样:C:\ file_name – flopex 2010-04-19 15:24:58