简体   繁体   中英

Printwriter making newlines out of spaces

I have a Reader reading in a file to edit it and save it afterwards with a printwriter. The start input is like this The problem is, that sometimes whitespaces are mistaken for new lines somehow like here . I goes even further in cutting it again after the first time like this

I have tried some different split characters, like
(what it actually is (you can see in System.out.println)) but I can´t get it to work properly

The Original loaded Textfile is this and the output of the getText is 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

It should just split on the string "<br>" and not on white spaces that are in between (in System.out.println it´s showing "Base" and then in a newline "Damage")

The following code runs fine for me, try to invoke the printToFile method and pass your String array to is as a parameter. By isolating the problematic code in a separate method it should be much easier to debug. I've also noticed you are comparing String objects with operators, this is not advised and doesn't do what you think it does. Read this answer for more information.

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

Output

these 
 lines 
should
 be  
 in   new 
line

Edit: What @DodgyCodeException mentioned in the comments could be the actual cause of your problem. For visibility sake I will just paste the comment:

The first 44 characters of the text are discarded because of your text.substring(44, text.length() - 16);. This includes everything up to "-- Base" (just before "Damage").

Complete solution

I've written a full solution to your problem in the following code. Try the code and see if it works for you then read the explanation posted underneath the code:

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

I've used Regex to find the text contained within the <body> tag of the input file you provided (the actual content we want is located in group 1 ) which was the part that was causing this problem. If you are further interested to see how the pattern included in this code works see this demo .

The rest of your code works fine so all you have to do is call the printToFile method and pass the return value of textPane.getText() as output String argument and it will process and print the required result for you to the text file located under a path of your choosing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM