【问题标题】:Get line separator of IFile获取 IFile 的行分隔符
【发布时间】:2013-02-04 09:03:08
【问题描述】:

我正在寻找一种方法来获取 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());

非常欢迎任何建议。

【问题讨论】:

  • 假设您的编程语言是 Java,对吗?不必在循环内声明您的 String final。此外,您不应使用连接运算符在 stringBuilder.append() 方法内连接字符串,这违背了该方法的目的。使用stringBuilder.append(nextLine),然后使用stringBuilder.append(System.lineSeparator())

标签: eclipse newline separator


【解决方案1】:

我想分享一个我偶然发现的解决方案:

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);

【讨论】:

    【解决方案2】:

    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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多