Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > Java программирование > Общие вопросы по Java, Java SE, Kotlin
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 21.12.2018, 09:39   #1
Nastya2018
Форумчанин
 
Регистрация: 24.07.2018
Сообщений: 133
По умолчанию Проблема с UTF 8

Написала код который конвертирует кириллицу в латиницу и выводит его в новом файле. Но там непонятные символы, как можно поменять код чтобы он записывал в файл в формате UTF-8?


Код:
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

        public class Main {
        public static void main(String[] args) throws  IOException { 
            
        //args.length
            
        System.out.println("argument = " + args[0]);
        System.out.println("argument = " + args[1]);  
        
        
        String inputFilePath = args[0];
        String outputFilePath = args[1];
        
        FileReader fileReader = new FileReader(inputFilePath);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        Writer writer = new OutputStreamWriter(new FileOutputStream(outputFilePath), StandardCharsets.UTF_8);
        
        String line;
        StringBuilder result = new StringBuilder();
        
        Map<String, String> dictionary = new Dictionary().getDictionary();
         
        
        while ((line = bufferedReader.readLine()) != null) {
            result.append(convertString(line, dictionary) + System.getProperty("line.separator")) ;
        }
        
        bufferedReader.close();
        fileReader.close();
        
        fileWriter.write(result.toString());
        fileWriter.flush();
        fileWriter.close();
        
        }
        

    public static String convertString(String str, Map<String, String> dictionary) {
        char[] chars = str.toCharArray();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            if (dictionary.containsKey(Character.toString(chars[i]))) {
                stringBuilder.append(dictionary.get(Character.toString(chars[i])));
                continue;
            }
            stringBuilder.append(chars[i]);
        }
        return stringBuilder.toString();
    }
}

class Dictionary {
    private Map<String, String> dictionary;

    public Dictionary() {
        dictionary = new HashMap<>();
        dictionary.put("а", "a");
        dictionary.put("А", "А");
        dictionary.put("ә", "á");
        dictionary.put("Ә", "Á");
        dictionary.put("б", "b");
        dictionary.put("Б", "B");
        dictionary.put("д", "d");
        dictionary.put("Д", "D");
        dictionary.put("е", "e");
        dictionary.put("E", "E");
        dictionary.put("ф", "f");
        dictionary.put("Ф", "F");
        dictionary.put("г", "g");
        dictionary.put("Г", "G");
        dictionary.put("ғ", "ǵ");
        dictionary.put("Ғ", "Ǵ");        
        dictionary.put("х", "h");
        dictionary.put("Х", "H");
        dictionary.put("h", "һ");
        dictionary.put("Һ", "Һ");
        dictionary.put("і", "i");
        dictionary.put("І", "І");
        dictionary.put("и", "ı");
        dictionary.put("И", "I");
        dictionary.put("й", "i");
        dictionary.put("Й", "I");
        dictionary.put("ж", "j");
        dictionary.put("Ж", "J");
        dictionary.put("к", "k");
        dictionary.put("К", "К");
        dictionary.put("л", "l");
        dictionary.put("Л", "L");
        dictionary.put("м", "m");
        dictionary.put("М", "M");
        dictionary.put("н", "n");
        dictionary.put("Н", "N");
        dictionary.put("ң", "ń");
        dictionary.put("Ң", "Ń");
        dictionary.put("о", "o");
        dictionary.put("О", "О");
        dictionary.put("ө", "ó");
        dictionary.put("Ө", "Ó");
        dictionary.put("п", "p");
        dictionary.put("П", "P");
        dictionary.put("қ", "q");
        dictionary.put("Қ", "Q");
        dictionary.put("р", "r");
        dictionary.put("Р", "R");
        dictionary.put("с", "s");
        dictionary.put("С", "S");
        dictionary.put("ш", "sh");
        dictionary.put("Ш", "Sh");
        dictionary.put("ч", "ch");
        dictionary.put("Ч", "Сh");
        dictionary.put("т", "t");
        dictionary.put("Т", "T");
        dictionary.put("ү", "ú");
        dictionary.put("Ү", "Ú");
        dictionary.put("ұ", "u");
        dictionary.put("Ұ", "U");
        dictionary.put("в", "v");
        dictionary.put("В", "V");
        dictionary.put("ы", "y");
        dictionary.put("Ы", "Y");
        dictionary.put("у", "ý");
        dictionary.put("У", "Ý");
        dictionary.put("з", "z");
        dictionary.put("З", "Z");
    }

    public Map<String, String> getDictionary() {
        return dictionary;
    }
}


И вот такая ошибка

Код:
Exception in thread "main" java.io.FileNotFoundException: C:\перевод\strings2a_kz.xml (Системе не удается найти указанный путь)
	at java.io.FileInputStream.open0(Native Method)
	at java.io.FileInputStream.open(FileInputStream.java:195)
	at java.io.FileInputStream.<init>(FileInputStream.java:138)
	at java.io.FileInputStream.<init>(FileInputStream.java:93)
	at java.io.FileReader.<init>(FileReader.java:58)
	at Main.main(Main.java:17)
C:\Users\Adil\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
СБОРКА ЗАВЕРШЕНА СО СБОЕМ (общее время: 0 секунд)
Nastya2018 вне форума Ответить с цитированием
Старый 24.12.2018, 08:57   #2
JavaDoc
Пользователь
 
Регистрация: 15.12.2018
Сообщений: 16
По умолчанию

Код:
 FileReader fileReader = new FileReader(inputFilePath);
здесь ты передаёшь путь к файлу
в данном случае система ругается что не может найти путь к файлу
JavaDoc вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Реально ли перевести UTF-16 в UTF-8, если да то как? FleXik Общие вопросы Delphi 7 28.09.2014 12:11
Проблема с utf-8 кодировкой Ale}{ander SQL, базы данных 1 16.09.2014 18:59
Win64, Windows Server 2008, Excel 2010-64 - проблема конвертации в UTF-8 Hugo121 Microsoft Office Excel 28 12.02.2013 16:48
Проблема с utf-8 в cmd Whiskas Windows 3 02.01.2013 13:17
Преобразовние Utf-16 <=> Utf-8 hard-t Общие вопросы C/C++ 1 26.08.2011 13:54