2

I understand that my question might be repeated, but I couldn't find the answer I need in other question's answer, I have a textArea where some data was appended there. and I want to write that data into a file with the same style of lines as in the textArea My textArea result looks like this

Type    Model   Serial      Country WTY START   WTY END     SER.STRT    SER.END     Int.Warrnty
1234    123    1234567      XXXXXX  2012-07-04  2015-07-03  2012-07-04  2015-07-03  Yes
5678    456    4567890      XXXXXX  2011-05-11  2014-06-24  ....-..-..  ....-..-..  No

When I try to write it to a text file it is written there like this after the yes, the second line is written immediately.

Type    Model   Serial      Country WTY START   WTY END     SER.STRT    SER.END     Int.Warrnty
1234    123    1234567      XXXXXX  2012-07-04  2015-07-03  2012-07-04  2015-07-03  Yes5678 456    4567890      XXXXXX  2011-05-11  2014-06-24  ....-..-..  ....-..-..  No

I tried to use print stream and file writer and all give the same, I tried as well buffered writer and add new line, still the same problem

my code for this is

String getTextArea_1 = textArea_1.getText();
String userHomeFolder = System.getProperty("user.home");
File file = new File(userHomeFolder, "RESULT_3.txt");
try {
    FileWriter fw = new FileWriter(file);
    fw.append(getTextArea_1);
    fw.flush();
    fw.close();
} catch (IOException e1) {
    e1.printStackTrace();
}

Thank you for your help

Markus Mitterauer
  • 1,560
  • 1
  • 14
  • 28
  • Debug your program, and check what line-breaks ('\r\n' or only '\r') you have in the variable `getTextArea_1` and if they are compatible with your systems. Maybe you have to replace them with the proper ones. – Markus Mitterauer Aug 09 '16 at 16:09
  • You may also have a look into `try-with-resources`. It does the `.close()` for you. -- https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html – Markus Mitterauer Aug 09 '16 at 16:11

2 Answers2

1

You need to append a \n after your first append, or you will write on same line

1

change your try-catch to something like this:

try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
    String[] strings = getTextArea_1.split("\n");
    for (String s : strings){
        writer.write(s);
        writer.newLine();        
    }
} catch (IOException e) {
    e.printStackTrace();
}
Sam
  • 7,778
  • 1
  • 23
  • 49
Eritrean
  • 15,851
  • 3
  • 22
  • 28
  • You are awesome man. I tried the same before, but I was declaring always the array before the try catch clauses and it never worked, thank you so much, it is a good lesson to learn ;) – Aboelmagd Saad Aug 10 '16 at 09:40