Considere o código seguinte: public static int copyWithFormat(Reader in, Writer out)…
- User
Considere o código seguinte:
public static int copyWithFormat(Reader in, Writer out) throws IOException { // WARNING : o ficheiro nao pode ser metido em memoria StringBuilder inputContent = new StringBuilder(); // Create a StringBuilder to store the input content char[] buffer = new char[1024]; // Create a buffer to read characters from the input reader int numRead; // Declare a variable to store the number of characters read while ((numRead = in.read(buffer)) != -1) { // While it is possible to read characters inputContent.append(buffer, 0, numRead); // Append the characters to the input content }
codeString inputString = inputContent.toString(); // Convert the input content to a string StringBuilder outputContent = new StringBuilder(); // Create a StringBuilder to store the output content int dotCount = 0; // Initialize a counter for the number of dots added int lastEnd = 0; // Initialize a variable to store the last end position for (int i = 0; i < inputString.length(); i++) { // Iterate over the characters of the input string char c = inputString.charAt(i); // Get the character at the current position if (Character.isDigit(c)) { // If the character is a digit int start = i; // Store the start position while (i < inputString.length() && Character.isDigit(inputString.charAt(i))) { // While the character is a digit i++; // Increment the position } String digits = inputString.substring(start, i); // Get the numeric sequence StringBuilder formattedDigits = new StringBuilder(digits); // Create a StringBuilder with the numeric sequence for (int j = digits.length() - 3; j > 0; j -= 3) { // Iterate over the digits in reverse order formattedDigits.insert(j, '.'); // Insert a dot every three digits dotCount++; // Increment the dot count } outputContent.append(formattedDigits); // Append the formatted digits to the output content lastEnd = i; // Update the last end position } else { outputContent.append(c); // Append the character to the output content } } outputContent.append(inputString.substring(lastEnd)); // Append the remaining characters to the output content out.write(outputContent.toString()); // Write the output content to the output writer return dotCount; // Return the number of dots added } - Assistant