印刷作家用空格代替换行符

时间:2019-06-03 15:12:10

标签: java printwriter

我有一个Reader来读取文件,以对其进行编辑并在以后使用printwriter保存。 开始输入就像this 问题是,有时空白会被误认为是新行,例如here。第一次之后我又进一步削减了 像this

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

原始加载的文本文件为this,而getText的输出为this

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

它应该仅在字符串"<br>"上而不是在中间的空格上分割(在System.out.println中,它显示“ Base”,然后在换行符“ Damage”中显示)

1 个答案:

答案 0 :(得分:0)

以下代码对我来说运行正常,请尝试调用printToFile方法并将String数组传递给is作为参数。通过用单独的方法隔离有问题的代码,它应该更容易调试。我还注意到您正在将String对象与运算符进行比较,不建议这样做,也不会按照您的想法去做。阅读此answer了解更多信息。

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可能是导致问题的实际原因。出于可见性考虑,我将只粘贴评论:

  

由于您的text.substring(44,text.length()-16);,该文本的前44个字符被丢弃。这包括直到“-Base”(在“ Damage”之前)的所有内容。

完整的解决方案

我在以下代码中为您的问题写了完整的解决方案。试试看代码,看看它是否对您有用,然后阅读代码下方的说明:

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

我已经使用Regex查找了您提供的输入文件的<body>标记中包含的文本(我们想要的实际内容位于group 1中)< / em>是导致此问题的部分。如果您还想了解此代码中包含的模式如何工作,请参阅此demo

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