Search code examples
javaprintwriterchars

PrintWriter writes something strange to txt


I wanted this program to write UTF-8 letters in .txt file but as a result i have numbers and other non-sense chars. Could anyone help me to solve it? I have no idea how to make it in print writer. I'll appreciate any help. Here's my code.

//all imports

public class Main extends Application {

    Stage okno;
    TableView<Produkt> tabela;
    TextField nazwaWejscie, iloscWejscie;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        okno = primaryStage;
        okno.setTitle("Stwórz listę zakupów");

        // Kolumna nazwa
        TableColumn<Produkt, String> kolumnaNazwa = new TableColumn<>("Nazwa");
        kolumnaNazwa.setMinWidth(200);
        kolumnaNazwa.setCellValueFactory(new PropertyValueFactory<>("nazwa"));

        // Kolumna ilosc
        TableColumn<Produkt, Double> kolumnaIlosc = new TableColumn<>("Ilość");
        kolumnaIlosc.setMinWidth(100);
        kolumnaIlosc.setCellValueFactory(new PropertyValueFactory<>("ilosc"));

        // Wprowadź nazwę
        nazwaWejscie = new TextField();
        nazwaWejscie.setPromptText("Nazwa (string)");
        nazwaWejscie.setMinWidth(100);

        // Wprowadź ilość
        iloscWejscie = new TextField();
        iloscWejscie.setPromptText("Ilość (double)");

        // Przyciski
        Button dodaj = new Button("Dodaj");
        dodaj.setOnAction(e -> kliknijDodaj());
        Button usun = new Button("Usuń");
        usun.setOnAction(e -> kliknijUsun());

        Button stworzListe = new Button("Zapisz listę");
        stworzListe.setOnAction(e -> zapiszListe());

        HBox pojemnik = new HBox();
        pojemnik.setPadding(new Insets(10, 10, 10, 10));
        pojemnik.setSpacing(10);
        // wstaw pola i przyciski w jeden rząd
        pojemnik.getChildren().addAll(nazwaWejscie, iloscWejscie, dodaj, usun, stworzListe);

        tabela = new TableView<>();
        tabela.setItems(getProdukt());
        tabela.getColumns().addAll(kolumnaNazwa, kolumnaIlosc);

        VBox vBox = new VBox();
        vBox.getChildren().addAll(tabela, pojemnik);

        Scene scena = new Scene(vBox);
        okno.setScene(scena);
        okno.show();
    }

    // Funkcja dodania produktu
    public void kliknijDodaj() {
        Produkt Produkt = new Produkt();
        Produkt.setNazwa(nazwaWejscie.getText());
        Produkt.setIlosc(Double.parseDouble(iloscWejscie.getText()));
        tabela.getItems().add(Produkt);
        nazwaWejscie.clear();
        iloscWejscie.clear();
    }

    // Funkcja usunięcia produktu
    public void kliknijUsun() {
        ObservableList<Produkt> ProduktWybrany, wszystkieProdukty;
        wszystkieProdukty = tabela.getItems();
        ProduktWybrany = tabela.getSelectionModel().getSelectedItems();

        ProduktWybrany.forEach(wszystkieProdukty::remove);
    }

    public ObservableList<Produkt> getProdukt() {
        ObservableList<Produkt> produkty = FXCollections.observableArrayList();
        return produkty;
    }

    // Funkcja dodania listy do pliku
    public void zapiszListe() {

        ArrayList<Produkt> produkty = new ArrayList<Produkt>(tabela.getItems());
        int licznik = 1;
        try {
            File plik = new File("C:\\Users\\Sebastian\\Desktop\\lista.txt");
            if (!plik.exists()) {
                plik.createNewFile();
            }
            FileWriter fw = new FileWriter(plik, true);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter pw = new PrintWriter(bw);
            for (int i = 0; i < produkty.size(); i++) {
                pw.println(licznik + ". " + produkty.get(i));
                licznik++;
            }
            pw.close();

        } catch (IOException ex) {
            System.out.println("Błąd: ");
            ex.printStackTrace();
        }

    }
}

Solution

  • This is because the FileWriter uses the default encoding as mentioned in the javadoc I quote:

    The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable.

    You need to define explicitly the encoding as next for example:

    Writer writer = new OutputStreamWriter(new FileOutputStream(plik, true), "UTF-8");
    

    The second problem in your code is related to the fact that you print licznik + ". " + produkty.get(i) which does a String concatenation of an integer, ". " and an object of type Produkt for which you obviously did not override the method toString() which means that it calls the default implementation defined in Object that only returns the name of the class followed by @ and the hash code of the object in hexadecimal. In other words, to fix your problem simply implement your own toString method in Produkt