2

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")

Nova
  • 21
  • 1
  • 4
  • Maybe the newline is a real part of the original data? – DodgyCodeException Jun 03 '19 at 15:19
  • When I first load the data in it´s without the newline, the newline comes in after saving it and reloading it again – Nova Jun 03 '19 at 15:20
  • 1
    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"). – DodgyCodeException Jun 03 '19 at 15:28
  • the first (and last) characters are the html tags for html, head & body, that I don´t want to be saved, but I´ll take a look at that again, if I have cutted of too much maybe – Nova Jun 03 '19 at 15:38
  • @Nova I've updated my answer to provide a complete solution to your problem. Let me know via comments if it works for you. – Matthew Jun 03 '19 at 16:25

1 Answers1

0

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.

Matthew
  • 1,905
  • 3
  • 19
  • 26
  • I have put the code in a separate method as you advised and also swapped the operators and the problem seems to come from the string split method – Nova Jun 03 '19 at 15:35
  • Yea I think the cause of your problem comes from either `text.substring(44, text.length() - 16)` or from using the `split` operation. Can you please provide the full text that `textPane.getText()` method return and include it in your question. This way I can run the test myself and give you a complete answer as to what is the problem. Might be best to post the text on PasteBin or somewhere like that and then provide a link not to clutter the question too much. – Matthew Jun 03 '19 at 15:38
  • I´ve added it now – Nova Jun 03 '19 at 15:43
  • I made it work with your solution, but it still does this weird linebreak :( oh and what is the getInputFileContent method for? I don´t have to use it to make it work löike before – Nova Jun 03 '19 at 17:24
  • Oh no you don't have to use that method it's just to read the content of a file and construct it into a single string. It is weird that you are still having the linebreak issue, I have used the same text you gave me and I don't have that problem. – Matthew Jun 03 '19 at 18:48
  • Can you please create a new Java project and use only this code with the text file that contains your HTML? If that works we can then eliminate this code from being the problem. – Matthew Jun 03 '19 at 18:49
  • I created a new Project and now everything is in there twice somehow, but it seems to still have the gap in there [pastebin](https://pastebin.com/ue4egFg0) – Nova Jun 03 '19 at 19:27