我正在寻找获取IFile对象的行分隔符的方法。 我当前的实现会在其他系统上编写文件的新行,但我非常依赖正确的偏移量和行号。
Scanner scanner = new Scanner(file.getContents());
StringBuilder stringBuilder = new StringBuilder();
while (scanner.hasNextLine()) {
final String nextLine = scanner.nextLine();
stringBuilder.append(nextLine + System.lineSeparator());
}
scanner.close();
Document document = new Document();
document.set(stringBuilder.toString(), document.getModificationStamp());
非常欢迎任何建议。
答案 0 :(得分:0)
我想分享一个我偶然发现的解决方案:
InputStream stream = file.getContents();
Scanner s = new Scanner(stream);
s.useDelimiter("\\A");
String content = s.hasNext() ? s.next() : null;
try {
stream.close();
s.close();
} catch (IOException e) {
}
if (content == null) {
return null;
}
IDocument document = new Document();
document.set(content);
答案 1 :(得分:0)
请参阅org.eclipse.core.filebuffers.manipulation.ConvertLineDelimitersOperation.computeTextEdit(ITextFileBuffer, IProgressMonitor)
。它使用IDocument.getLineDelimiter(int)
方法计算文件中的行分隔符。
你可能会看到类似的东西:
ITextFileBufferManager manager = FileBuffersPlugin.getFileBufferManager();
ITextFileBuffer buffer = manager.getTextFileBuffer(file.getLocation());
IDocument document = buffer.getDocument();
int lineCount = document.getNumberOfLines();
for(int i = 0; i < lineCount; i++) {
String delimiter = document.getLineDelimiter(i);
// your work here
}