There is a block of code that reads a line from a file and the line will be in Russian, but accordingly in the terminal instead of Russian letters there are question marks, and in English it is normal to output, as I understand the problem with encodings, how can you solve this problem?

public static void HabitFileReader() { try { FileReader fReader = new FileReader("C:/ProgramData/Tracker Habits/Habit List.txt"); Scanner fScanner = new Scanner(fReader); while (fScanner.hasNext()) { Habit1 = fScanner.nextLine(); System.out.println("Line 1 - " + Habit1); fReader.close(); } } catch (IOException e) { System.out.println("\nFile read error"); } } 

Write code block:

  public static void FileWriter() { try { FileWriter fWriter = new FileWriter("C:/ProgramData/KateProgram/date.txt"); fWriter.write(General.Writer); System.out.println("File successfully write"); fWriter.close(); System.out.println("Program complete"); }catch (IOException e) { System.out.println("File write error"); } } 

    1 answer 1

    Recently a similar question asked, on unloading from the database. In a regular reader, I can assume that the file that is in text format is not UTF-8. You put the code where you read the file. But there is no code where you write it. Of course, you can specify the encoding when reading, but these are extra lines of code. It is better to immediately write the file to UTF-8; Then, as an option, it can be in pom, but it is UTF-8 standard. It is unlikely that there you nakosyachil. Found an example in Google:

    For the record:

     File file = new File("test.txt"); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8")); 

    For reading:

     File file = new File("test.txt"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8")); 
    • Yes, it will be easier to write down the encodings at the time of the recording, here is the block of the recording code: I added a block of the file recording in the code to the question. - Andrew
    • And for FileWriter, is it possible to immediately specify the encoding of the entry? - Andrew
    • @Andrew found the answer, now I will update. - Alexey Zemtsov
    • @Andrew is like that. - Alexey Zemtsov
    • It turns out then the record needs to be done through BufferedReader, and not through FileWriter? - Andrew