Итак, я создал код, который должен запрашивать у пользователя имя файла.Если имя файла существует, предполагается, что он выполняет следующие действия:
Прописать первую букву в файле и заглавную 1-ю букву после каждого периода и исправить интервал, удалив все повторяющиеся пробелы, чтобы оставалось только 1пробел между словами.
Записать измененный вывод в файл с именем HomeworkOutput6-2.txt.
Я смог сделать это полностью, но у меня возникла одна КРАЙНЯ проблема, которую я не знаю, какtackle.
ЕСЛИ в файле пользователя было только 2 строки.Измененный файл имеет третью пустую ссылку.Как я могу исключить эту третью лишнюю строку.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class ReadAndEditFile {
public static void main(String[] args) throws IOException {
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
File file = null;
// keep asking for a file name until we get a valid one
while (true) {
System.out.println("What is the name of your file?");
String fileName = scanner.nextLine();
file = new File(fileName);
if (file.exists()) {
//enter code here
break;
} else {
System.out.println("File Not Found " + fileName);
}
}
scanner.close();
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
PrintWriter writer = new PrintWriter(new FileWriter("HomeworkOutput6-2.txt"));
boolean firstLine = true;
while ((line = br.readLine()) != null) {
if (firstLine && line.length() > 0) {
// capitalize 1st letter of first line
line = Character.toUpperCase(line.charAt(0)) + line.substring(1);
firstLine = false;
}
line = capitalize(line);
writer.println(line);
}
writer.close();
br.close();
}
// remove extra spaces and capitalize first letter after a period
private static String capitalize(String line) {
line = line.replaceAll(" +", " "); // make all multiple spaces as a single space
StringBuilder sb = new StringBuilder();
boolean periodFound = false;
int i = 0;
while (i < line.length()) {
char c = line.charAt(i);
if (c == '.') {
periodFound = true;
}
sb = sb.append(c);
if (periodFound) {
// period is found. Need to capitalize next char
if (i + 1 < line.length()) {
c = line.charAt(i + 1);
if (Character.isLetter(c)) {
sb = sb.append(Character.toUpperCase(c));
i++;
} else if (Character.isSpaceChar(c) && (i + 2 < line.length())) {
// there is a space after period. Capitalize the next char
sb = sb.append(c); // append space. Note we will have only 1 space at max
sb.append(Character.toUpperCase(line.charAt(i+2))); // upper case next char
i = i+2;
}
}
periodFound = false;
}
i++;
}
return sb.toString();
}}