为你的工程或工作空间设置编码

来源:互联网 发布:建立数学模型软件 编辑:程序博客网 时间:2024/06/04 23:31
新的工作中有这个需求,于是研究了一番。我们知道,在Eclipse首先项中就有改变工作空间编码的功能。截图如下:

注意 Text file encoding那里。
好吧,程序员最不缺乏的就是钻研精神,将eclipse此处的源码阅读一下不就清楚了吗。
在我阅读代码的过程中依次寻找的类是:
IDEWorkspacePreferencePage--->ResourceEncodingFieldEditor
找到doStore方法:
protected void doStore() {
String encoding = getSelectedEncoding();
// Clear the value if nothing is selected
if (isDefaultSelected()) {
encoding = null;
}
// Don't update if the same thing is selected
if (hasSameEncoding(encoding)) {
return;
}
String descriptionCharset = getCharsetFromDescription();
if (descriptionCharset != null
&& !(descriptionCharset.equals(encoding)) && encoding != null) {
Shell shell = null;
DialogPage page = getPage();
if (page != null) {
shell = page.getShell();
}
                //为缩短文章篇幅,删掉了部分代码
IDEEncoding.addIDEEncoding(encoding);
final String finalEncoding = encoding;
                 //改变编码的地方在这里
Job charsetJob = new Job(IDEWorkbenchMessages.IDEEncoding_EncodingJob) {
protected IStatus run(IProgressMonitor monitor) {
try {
if (resource instanceof IContainer) {
                                                  //核心方法就是setDefaultCharset
((IContainer) resource).setDefaultCharset(
finalEncoding, monitor);
} else {
((IFile) resource).setCharset(finalEncoding, monitor);
}
return Status.OK_STATUS;
} catch (CoreException e) {// If there is an error return the
// default
IDEWorkbenchPlugin
.log(
IDEWorkbenchMessages.ResourceEncodingFieldEditor_ErrorStoringMessage,
e.getStatus());
return e.getStatus();
}
}
};
charsetJob.schedule();
}
//1.设置工作空间的编码
ResourcesPlugin.getWorkspace().getRoot().setDefaultCharset("编码", monitor)

//2.设置工程编码
private void setProjectCharset() {
try {
getJavaProject().getProject().setDefaultCharset("utf-8",
new NullProgressMonitor());
} catch (CoreException e1) {
e1.printStackTrace();
}
}