-3

I created csv file in Java and inserted some values.This is source

try {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate localDate = LocalDate.now();
        System.out.println(dtf.format(localDate).toString() + ".csv");

        String filename = dtf.format(localDate).toString() + ".csv";


        StringBuilder builder = new StringBuilder();

        if (Files.exists(Paths.get("D:\\" + filename))) {
            System.out.println("File existed");

        } else {
            System.out.println("File not found!");
            String ColumnNamesList = "UID,name,personalNumber,nationality,dateofbirth,dateofexp,documentcode,gender,issueState,documentType";
            builder.append(ColumnNamesList + "\n");

        }
        builder.append(UID + ",");
        builder.append(name + ",");
        builder.append(personalNumber + ",");
        builder.append(nationality + ",");
        builder.append(dateofbirth + ",");
        builder.append(dateofexp + ",");
        builder.append(documentcode + ",");
        builder.append(gender + ",");
        builder.append(issueState + ",");
        builder.append(documentType + ",");

        builder.append('\n');

        File file = new File("D:\\" + filename);
        FileWriter fw = new FileWriter(file, true); // the true will append the new data
        fw.write(builder.toString());
        fw.close();
        System.out.println("done!");

    } catch (IOException ioe) {
        System.err.println("IOException: " + ioe.getMessage());
    }

Problem is that,my "name" value is not English alphabet and result in my file is null. Is it a possible to add uft-8 support StringBuilder ? or how i can save some values in file with uft-8? thanks

BekaKK
  • 2,173
  • 6
  • 42
  • 80
  • 3
    See [How to write a UTF-8 file with Java? ](https://stackoverflow.com/questions/1001540/how-to-write-a-utf-8-file-with-java) – rossum Aug 05 '17 at 14:16
  • Note that nowadays we should use Javas new I/O API called **NIO**. It is more robust, has more to offer and is easier to read. And, which is of special interest to you, it automatically reads and writes everything in **UTF-8**, if not specified otherwise. Its main classes are `Files` and `Paths`. You already used them for reading but you should also use them for **writing**. With the old API you **always** need to specify the encoding to use, for example `StandardCharsets.UTF_8`, else they will use the platforms default encoding which often is not **UTF-8**. – Zabuzard Aug 05 '17 at 15:09
  • 1
    Give COMPLETE verifiable code. Without 'name' declaration and initialisation answer is impossible. Correct use of Java IO have no problem with encoding (I write non-english software whole life) – Jacek Cz Aug 05 '17 at 16:24

1 Answers1

-2

Try this:

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