文学作家和阅读

问题描述 投票:0回答:1

所以我创建了一个代码,假设要求用户输入文件名。如果文件名确实存在,则假定执行以下操作:

大写文件中的第一个字母并在每个句点之后将第一个字母大写,并通过删除任何重复的空格来更正间距,以便在单词之间只有1个空格。

将修改后的输出写入名为HomeworkOutput6-2.txt的文件。

我能够完全做到这一点,但有一个非常轻微的问题,我不知道如何解决。

如果用户文件只有2行。修改后的文件有第三个空白链接。我怎么能消除第3条额外线。

        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();

} }

java filewriter
1个回答
0
投票

你的逻辑是完美但复杂的。我建议你写简单的逻辑,因为如果你得到任何错误你可以轻松解决。而不是使用循环和复杂,我已根据你的要求编写简单的逻辑。

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();
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.