提问者:小点点

印刷工人在空格外换行


我有一个阅读器读取一个文件进行编辑,然后用打印机保存。开始输入是这样的问题是,有时空白会被误认为是新行,就像这里一样。在第一次像这样剪完之后,我还会再剪一次

我已经尝试了一些不同的拆分字符,例如(
它实际上是什么(您可以在System.out.println中看到)),但我无法让它正常工作

最初加载的文本文件是这样的,getText的输出是这样的

if (lastClicked != 0) {
                    String path;
                    switch (lastClicked) {
                    case 1:
                        path = "data/alyxia_status.got";
                        break;
                    case 2:
                        path = "data/mog_status.got";
                        break;
                    case 3:
                        path = "data/telias_status.got";
                        break;
                    default:
                        path = "data/tiernen_status.got";
                    }
                    String text = textPane.getText();                   
                    String toWrite = text.substring(44, text.length() - 16);
                    System.out.println(toWrite);
                    String[] parts = toWrite.split("<br>");

                    FileWriter fileWriter;
                    try {
                        fileWriter = new FileWriter(path);
                        PrintWriter printWriter = new PrintWriter(fileWriter);
                        printWriter.print(parts[0]);
                        for (int i = 1; i<parts.length; i++) {  
                            if (parts[i] != "" && parts[i] != " ") {
                                printWriter.println();                              
                                printWriter.print(parts[i]);
                            }
                        }

                        printWriter.close();
                    } catch (IOException e1) {                      
                        e1.printStackTrace();
                        System.err.println("Saving failed");
                    }

                }//end if

它应该只是在字符串上分裂


共1个答案

匿名用户

以下代码对我来说运行良好,尝试调用 printToFile 方法并将您的字符串数组作为参数传递给 is。通过在单独的方法中隔离有问题的代码,调试应该容易得多。我还注意到您正在将 String 对象与运算符进行比较,不建议这样做,也不会执行您认为它的作用。阅读此答案以获取更多信息。

public static void printToFile(String path, String[] output) {

    FileWriter fileWriter;
    try {
        fileWriter = new FileWriter(path);
        PrintWriter printWriter = new PrintWriter(fileWriter);
        printWriter.print(output[0]);
        for (int i = 1; i < output.length; i++)
        {
            /* DO NOT compare string with opeators like "!=" or "==,
             * instead use equals method to properly compare them
             */
            if (!output[i].equals("") && !output[i].equals(" ")) {
                printWriter.println();
                printWriter.print(output[i]);
            }
        }
        printWriter.close();
    }
    catch (java.io.IOException e1) {
        e1.printStackTrace();
        System.err.println("Saving failed");
    }
}

public static void main(String[] args) throws IOException
{
    Path path = Paths.get("sample.txt");
    String[] text = new String[] { "these ", " lines ", "should", " be  ", " in   new ", "line" };

    printToFile(path.toString(), text);
    Files.readAllLines(path).forEach(System.out::println);
}

输出

these 
 lines 
should
 be  
 in   new 
line

编辑:评论中提到的@DodgyCodeException可能是你的问题的真正原因。为了便于查看,我将只粘贴注释:

文本的前 44 个字符被丢弃,因为你的 text.substring(44, text.length() - 16);。这包括“--基础”(就在“伤害”之前)的所有内容。

完全解

我在以下代码中为您的问题编写了完整的解决方案。尝试代码,看看它是否适合您,然后阅读代码下方发布的说明:

public class Main {

    /**
     * Use {@link StringBuilder} to build a single {@code String}
     * from the read contents of file located under given path.
     * 
     * @param path {@code Path} of the file to read
     * @throws IOException if an I/O error occurs reading from the file
     *         or a malformed or unmappable byte sequence is read.
     */
    private static String getInputFileContent(Path path) throws IOException {

        StringBuilder sb = new StringBuilder();
        Files.readAllLines(path).forEach(sb::append);
        return sb.toString();
    }

    /**
     * @return the matched content contained in <body> tag within
     *         the provided text or {@code null} if there was no match.
     */
    private static @Nullable String getHTMLBodyFromText(String text) {

        Pattern pattern = Pattern.compile("(?:\\s*?<body>)(?:\\s*)((.*\\s)*)</body>");
        Matcher matcher = pattern.matcher(text);
        return matcher.find() ? matcher.group(1) : null;
    }

    public static void printToFile(Path path, String output) {

        String toWrite = getHTMLBodyFromText(output);
        if (toWrite == null) {
            System.err.println("Unable to find body");
            return;
        }
        String[] parts = toWrite.split("<br>");
        FileWriter fileWriter;
        try {
            fileWriter = new FileWriter(path.toString());
            PrintWriter printWriter = new PrintWriter(fileWriter);
            printWriter.print(parts[0]);
            for (int i = 1; i < parts.length; i++)
            {
                /* DO NOT compare string with opeators like "!=" or "==,
                 * instead use equals method to properly compare them
                 */
                if (!parts[i].equals("") && !parts[i].equals(" ")) {
                    printWriter.println(parts[i]);
                    printWriter.print(parts[i]);
                }
            }
            printWriter.close();
        }
        catch (java.io.IOException e1) {
            e1.printStackTrace();
            System.err.println("Saving failed");
        }
    }
    public static void main(String[] args) throws IOException
    {
        Path inputPath = Paths.get("input.txt");
        Path outputPath = Paths.get("output.txt");

        printToFile(outputPath, getInputFileContent(inputPath));
    }
}

我使用了< code>Regex来查找< code >中包含的文本

其余代码工作正常,因此您所要做的就是调用printToFile方法并将textPane.gettext()的返回值作为输出String参数传递,它将为您处理并打印所需的结果到位于您选择的路径下的文本文件中。