Search code examples
javafiletesseract

Java How to Write Spesific String to Txt File Line By Line(Tesseract Output)


I need to print my result string line by line to TXT file. Here is my code:

        try {

        String result = instance.doOCR(imageFile);
        FileWriter writer = new FileWriter("C:\\testfiles\\enes.txt");
        try(PrintWriter printWriter = new PrintWriter(writer)){
                //printWriter.write(result);
                printWriter.println(result);
}
        System.out.println(result);
    } catch (Exception e) {
        System.err.println(e.getCause());
    }

Also my console output is like this:

İbrahim Enes ALAN

Küçükbakkalköy, 2. Hazine Sk., 34750 Ataşehir/İstanbul Efo Academic Aparts Tel. No: (542)6299228

E-mail: en@ozu.edu.tr / en@hotmail.c0m

As you can see my console output printed line by line which is I want.But in my txt file all words in one line.How can I print like my console output. Do you have any suggestions? Thanks for your help.


Solution

  • You need to invoke printWriter.write("\r\n"); or printWriter.write(System.lineSeparator()) depends on your operation system

    try {
    
        String result = instance.doOCR(imageFile);
        FileWriter writer = new FileWriter("C:\\testfiles\\enes.txt");
        try(PrintWriter printWriter = new PrintWriter(writer)){
        printWriter.write(result);
        printWriter.write("\r\n");
    }
       System.out.println(result);
    } catch (Exception e) {
            System.err.println(e.getCause());
    }