I wrote a java code which divides the line through the words of the text so that each substring of no more than MaxWidth. It exelent working, but much slow. Help to optimize! Here's the code:
Pattern pattern = Pattern.compile("(.{1," + symbols + "}(\\b|\\s))"); // symbols - MaxWidth
Pattern pattern2 = Pattern.compile("\\s.*");
while ((line = in.readLine()) != null) { // reading file by lines
String dopLine = "";
if (pattern2.matcher(line).matches()) {
// If a line begins with a space, it is the beginning of a paragraph and need to add \ n
if(!tempDopLine.equals("")) { // tempDopLine - Some part of the previous line, which is not full screen
tempStringBuffer.append(tempDopLine);
tempStringBuffer.append("\n");
lineCounter++;
if (lineCounter == lines) {
addPage(tempStringBuffer); // create page
tempStringBuffer = new StringBuilder("");
lineCounter = 0;
numberOfPages++;
}
}
tempDopLine = "";
dopLine = line;
} else {
dopLine = tempDopLine + " " + line; // if this line
}
Matcher matcher = pattern.matcher(dopLine); // divide a string into a substrings
HashMap<Integer, String> temp = new HashMap<Integer, String>();
int i = 0;
while (matcher.find()) {
temp.put(i, matcher.group());
i++;
}
for(i = 0; i < temp.size(); i++) {
if (i<(temp.size()-1)) {
String tempL = temp.get(i);
tempStringBuffer.append(tempL);
tempStringBuffer.append("\n");
lineCounter++;
if (lineCounter == lines) {
addPage(tempStringBuffer);
tempStringBuffer = new StringBuilder("");
lineCounter = 0;
numberOfPages++;
}
} else {
tempDopLine = temp.get(i); // The last part of the string remember to display it along with the next line
}
}
}
How you can optimize this code? Please help and sorry for my poor English.