简体   繁体   中英

PrintWriter printing “line.separator” twice in file

I have a method called saveAgendaDataArrayList() which is suposed to save the data from an ArrayList in a TXT file as following.

public void saveAgendaDataArrayList(String path, ArrayList<Contact> agendaDataArrayList) {
        try {
            if(agendaDataArrayList!=null) {
                File file = new File(path);
                PrintWriter p = new PrintWriter(file);

                int count = agendaDataArrayList.size();

                for(int i=0; i<count; i++) {
                    Contact temp = new Contact();
                    temp = agendaDataArrayList.get(i);
                    p.println(temp.getIdAdress()+";"+temp.getContactType()+";"+temp.getName()+";"+temp.getBirthdayDay()+
                            ";"+temp.getBirthdayMonth()+";"+temp.getBirthdayYear()+";"+temp.getTel1()+";"+temp.getTel2()+
                            ";"+temp.getNeigborhood()+";"+temp.getAddress()+";"+temp.getCep()+";"+temp.getEmail()
                            +";"+temp.getOtherInformation()+";"+temp.getCreationDate()+";");
                }
                p.close();

            } else {
                File file = new File(path);
                PrintWriter p = new PrintWriter(file);
                p.print("empty agenda");
                p.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

However, when it runs, I have some new lines coming from I don't know where. Look below.

1;1;Guilhermee;00;00;;8666666;;sem bairro;;;;;12-09-2019 04:45:47;

2;1;Gabriella;00;00;;;;Morada do Sol;;;;;12-09-2019 04:45:57;

3;1;joao;00;00;;;;sem bairro;;;;;12-09-2019 05:38:13;

4;1;lua;00;00;;;;sem bairro;;;;;12-09-2019 06:11:15;

5;1;roberto;00;00;;;;sem bairro;;;;;12-09-2019 06:12:22;

6;1;joquina;00;00;;;;Monte Verde;;;;;12-09-2019 07:38:30;

7;1;luan silva;00;00;;;;sem bairro;;;;;12-09-2019 07:40:07;

8;1;manoel;00;00;;89898989;;sem bairro;asdasd;;;;12-09-2019 07:44:44;

9;1;joana;19;01;1954;;;Cidade Jardim;;;;;12-09-2019 07:48:03;

10;1;mariana;00;00;;;;sem bairro;;;;;12-09-2019 07:57:43;

11;1;agoradeucerto;00;00;;;;Morros;;;;;12-09-2019 08:01:46;
12;1;mais uma tentativa;00;00;;;;sem bairro;;;;;12-09-2019 08:43:19;

I'd like to have an output file as above, but without the empty lines.

I tried to see if the same would happen in console with the method System.out.println() , and it happened there too.

Looking in a text file editor, the Notepad, I noticed there are some LF mixed with CR LF in the end of lines.

I've reviewed the Contact class and all seems to be right.

So, what could I do to reach that result and avoid those empty lines, and why only the last line is in the correct place?

Thank you for your time.

EDIT 1 - The input method

Here is the input method. There are 2 ways to add the data into agendaDataArrayList . The first one is through reading a txt file (1st method) and the second one, through an input interface (2nd method).

1st method

public ArrayList<Contact> getAgendaDataArrayList(String path) {
        try {
            FileReader reader = new FileReader(path);
            Scanner scanner1 = new Scanner(reader);
            scanner1.useDelimiter("\r\n|\n");
            int count = 0;
            while(scanner1.hasNext()) {
                scanner1.next();
                count++;
            }
            System.out.println(count);
            scanner1.close();
            reader.close();

            ArrayList<Contact> agendaDataArrayList = new ArrayList<Contact>();

            FileReader reader2 = new FileReader(path);
            Scanner scanner2 = new Scanner(reader2);
            scanner2.useDelimiter(";");

            for(int i=0; i<count; i++) {
                Contact temp = new Contact();               
                temp.setIdAdress(scanner2.next());          //[0]  id
                temp.setContactType(scanner2.next());       //[1]  type
                temp.setName(scanner2.next());              //[2]  name
                temp.setBirthdayDay(scanner2.next());       //[3]  birthdayDay
                temp.setBirthdayMonth(scanner2.next());     //[4]  birthdayMonth
                temp.setBirthdayYear(scanner2.next());      //[5]  birthdayYear
                temp.setTel1(scanner2.next());              //[6]  tel1
                temp.setTel2(scanner2.next());              //[7]  tel2
                temp.setNeigborhood(scanner2.next());       //[8]  neighborhood
                temp.setAddress(scanner2.next());           //[9]  address
                temp.setCep(scanner2.next());               //[10] cep
                temp.setEmail(scanner2.next());             //[11] email
                temp.setOtherInformation(scanner2.next());  //[12] other information
                temp.setCreationDate(scanner2.next());      //[13] creation date

                agendaDataArrayList.add(temp);
            }
            scanner2.close();
            reader2.close();
            return agendaDataArrayList;
        } catch (IOException e) {
            e.printStackTrace();
            ArrayList<Contact> agendaDataArrayList = new ArrayList<Contact>();
            return agendaDataArrayList;
        }
    }

2nd method

    public void saveActionButton() {
        Date creationDate = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        Contact newContact = new Contact();

        newContact.setIdAdress(mainApp.getNextIdAddress());

        if(typeChoiceBox.getValue()==null) {
            newContact.setContactType("1");
        } else {
            newContact.setContactType(typeChoiceBox.getValue());
        }

        if(nameTextField.getText()==null) {
            newContact.setName("sem nome");
        } else {
            newContact.setName(nameTextField.getText());
        }

        if(dayChoiceBox.getValue()==null) {
            newContact.setBirthdayDay("00");
        }else {
            newContact.setBirthdayDay(dayChoiceBox.getValue());
        }

        if(monthChoiceBox.getValue()==null) {
            newContact.setBirthdayMonth("00");
        }else {
            newContact.setBirthdayMonth(monthChoiceBox.getValue());
        }

        if(yearTextField.getText()==null) {
            newContact.setBirthdayYear("0000");
        }else {
            newContact.setBirthdayYear(yearTextField.getText());
        }

        if(tel1TextField.getText()==null) {
            newContact.setTel1("sem número");
        }else {
            newContact.setTel1(tel1TextField.getText());
        }

        if(tel2TextField.getText()==null) {
            newContact.setTel2("sem número");
        }else {
            newContact.setTel2(tel2TextField.getText());
        }

        if(neighborhoodChoiceBox.getValue()==null) {
            newContact.setNeigborhood("sem bairro");
        } else {
            newContact.setNeigborhood(neighborhoodChoiceBox.getValue());
        }

        if(addressTextField.getText()==null) {
            newContact.setAddress("sem endereço");
        } else {
            newContact.setAddress(addressTextField.getText());
        }

        if(cepTextField.getText()==null) {
            newContact.setCep("sem CEP");
        }else {
            newContact.setCep(cepTextField.getText());
        }

        if(emailTextField.getText()==null) {
            newContact.setEmail("sem e-mail");
        } else {
            newContact.setEmail(emailTextField.getText());
        }

        if(otherInfoTextArea.getText()==null) {
            newContact.setOtherInformation("sem mais informações");
        }else {
            newContact.setOtherInformation(otherInfoTextArea.getText());
        }

        newContact.setCreationDate(formatter.format(creationDate).toString());
        mainApp.addContactToAgendaDataArrayList(newContact);
        mainApp.refreshFullContentInMainLayout();
        mainApp.saveFile();

        Stage stage = (Stage) saveButton.getScene().getWindow();
        stage.close();
    }
}

Compare the first method output of the entries with id address 12 and the other ones that have new lines before them.

It is possible that some data are inserted on windows (therefore the CR LF whitespaces) and some on the unix system (which uses only LF). Anyway, it seems tha data itself contains new line marks, the PrinterWriter works as you would like. A small test:

import java.util.ArrayList;
import java.io.*;

public class Main {

    public static void main(String[] args) {
        System.out.println("Hello");  

        ArrayList<Contact> list = new ArrayList<>();
        list.add(new Contact());
        list.add(new Contact());
        list.add(new Contact());
        list.add(new Contact());
        list.add(new Contact());

        try {
                File file = new File("output.txt");
                PrintWriter p = new PrintWriter(file);

                int count = list.size();

                for (int i = 0; i < count; i++) {
                    Contact temp = list.get(i);
                    p.println(temp.getFavColour() + ";" + temp.getSurname() + ";" + temp.getName() + ";");
                }
                p.close();


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static class Contact {
        public String getName() {
            return "John";
        }

        public String getSurname() {
            return "Black";
        }

        public String getFavColour() {
            return "red";
        }
    }
}

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