File Writer и чтение - PullRequest
       26

File Writer и чтение

0 голосов
/ 10 апреля 2019

Итак, я создал код, который должен запрашивать у пользователя имя файла.Если имя файла существует, предполагается, что он выполняет следующие действия:

Прописать первую букву в файле и заглавную 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();

}}

1 Ответ

0 голосов
/ 10 апреля 2019

ваша логика идеальна, но сложна. Я предлагаю вам написать простую логику, потому что, если вы получаете любую ошибку, вы можете легко ее решить. Вместо использования цикла и сложных, я написал простую логику в соответствии с вашими требованиями.

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ReadAndEditFile2 {

    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        File file = null;
        boolean createOutputFile = false;
        // 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()) {

                /**
                 * read all files lines and convert to stream
                 */
                Stream<String> lines = Files.lines(file.toPath());
                String data = lines.collect(Collectors.joining("\n"));
                /**
                 * split all lines with dot(.)
                 */
                String[] sepratedData = data.split("\\.");
                String test = "";
                for (String seprateString : sepratedData) {
                    /**
                     * trim() will remove all space at begin and end of string,
                     */
                    seprateString = seprateString.trim();
                    /**
                     * convert first character to UpperCase
                     */
                    if (!seprateString.isEmpty()) {
                        seprateString = Character.toUpperCase(seprateString.charAt(0)) + seprateString.substring(1);
                        test += seprateString + "."+"\n";
                        createOutputFile = true;
                    }

                }
                /**
                 * remove more than one space to single space
                 */
                if (createOutputFile) {
                    test = filter(test, " [\\s]+", " ");
                    Files.write(Paths.get("HomeworkOutput6-2.txt"), test.getBytes());
                    lines.close();
                }

                break;
            } else {
                System.out.println("File Not Found " + fileName);
            }
        }

    }

    public static String filter(String scan, String regex, String replace) {
        StringBuffer sb = new StringBuffer();

        Pattern pt = Pattern.compile(regex);
        Matcher m = pt.matcher(scan);

        while (m.find()) {
            m.appendReplacement(sb, replace);
        }

        m.appendTail(sb);

        return sb.toString();
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...