e969. retrieving all the text from a jtextcomponent efficiently.txt
来自「这里面包含了一百多个JAVA源文件」· 文本 代码 · 共 37 行
TXT
37 行
The text contained in a text component is not always stored contiguously. Therefore, retrieving text using getText() may cause a new String object to be created and the text copied to the new string. If you do not need the text in one contiguous chunk, the most efficient way to retrieve the text is in pieces called segments. This example retrieves the entire contents of a text component in segments.
// Create the text component
JTextComponent textComp = new JTextPane();
Document doc = textComp.getDocument();
// Create a segment to hold the characters in the document
Segment segment = new Segment();
int pos = 0;
segment.setPartialReturn(true);
try {
// Retrieve all segments
while (pos < doc.getLength()) {
// Ask for the remainder of the document text
doc.getText(pos, doc.getLength()-pos, segment);
// You can access the contents directly from the array in the segment.
// Never modify the contents of the array
for (int i=0; i<segment.count; i++) {
int positionInDoc = pos+i;
char charAtPos = segment.array[i+segment.offset];
}
// Or use the segment as a character iterator
int i=0;
for(char c=segment.first(); c != CharacterIterator.DONE; c=segment.next(), i++) {
int positionInDoc = pos+i;
char charAtPos = c;
}
// Increment pos by the actual number of characters retrieved
pos += segment.count;
}
} catch (BadLocationException e) {
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?