Русские Блоги
Команды javac и java наиболее нам знакомы, в javac есть параметр -encoding? , Который используется для компиляции файла .java в файл .class; java имеет параметр -D’file.encoding =? ‘, Который используется для запуска файла .class; и наш файл .java Также у него есть собственный метод кодирования. По умолчанию и javac, и java являются GBK.
Кодировка файла UTF8.java — UTF-8:
import java.nio.charset.Charset; public class UTF8 < public static void main(String[] args) < System.out.println("file.encoding=" + System.getProperties().getProperty("file.encoding")); System.out.println ("По умолчанию:" + Charset.defaultCharset (). Name ()); >>
Метод кодирования файла GBK.java — GBK:
import java.nio.charset.Charset; public class GBK < public static void main(String[] args) < System.out.println("file.encoding=" + System.getProperties().getProperty("file.encoding")); System.out.println ("По умолчанию:" + Charset.defaultCharset (). Name ()); >>
Примечание. System.getProperties (). GetProperty («file.encoding») и Charset.defaultCharset (). Name () — это методы кодирования для возврата команд Java.
Кодировка файла и кодировка команды javac — оба GBK, и программа работает без проблем.
Кодировка файла и кодировка команды javac — UTF-8, и программа работает без проблем.
Кодировка файлов UTF-8 и кодировка команд javac GBK, китайский искаженный.
Кодировка файла GBK и кодировка команды javac UTF-8, компиляция не выполняется.
Это видно из приведенных выше 4 Liezi:Кодировка файла и кодировка команды javac должны быть одинаковыми, а метод кодирования команды java является произвольным. Но когда программа читает файлы, данные сетевых запросов и т. Д., Будут случаи, когда входной поток преобразуется в подстроки. В это время можно использовать Charset.defaultCharset (), а Charset.defaultCharset () получает метод кодирования команды java. несмотря на то чтоМетод кодирования java-команд произвольный, но лучше, чтобы он совпадал с двумя другими кодировками, чтобы облегчить память.
Например, один и тот же .class будет иметь разные результаты при разных методах кодирования команд java.
Метод кодирования файла Test.java GBK
import java.io.BufferedReader; import java.io.FileReader; import java.nio.charset.Charset; public class Test < public static void main(String[] args) throws Exception < System.out.println("file.encoding=" + System.getProperties().getProperty("file.encoding")); System.out.println ("По умолчанию:" + Charset.defaultCharset (). Name ()); FileReader fileReader = new FileReader ("C: /UTF8.java"); // метод кодировки UTF8.java UTF-8 BufferedReader bufferedReader = new BufferedReader(fileReader); StringBuilder stringBuilder = new StringBuilder(); String temp = null; while ((temp = bufferedReader.readLine()) != null) < stringBuilder.append(temp); >System.out.println(stringBuilder.toString()); bufferedReader.close(); fileReader.close(); > >
идея проекта Maven:
Настройки кодировки файлов:
Параметры кодировки команды javac:
Параметры кодировки команды java:
UTF8 filenames with Java
Functions from java.io solely depend on the locale settings of your operating system. If you want to create the directory /tmp/foö/bär, save this snippet to a file called javaapplication1/JavaApplication1.java:
package javaapplication1; public class JavaApplication1 < static < System.setProperty("file.encoding", "UTF-8"); System.setProperty("sun.jnu.encoding", "UTF-8"); >public static void main(String[] args) < new java.io.File("/tmp/foö/bär").mkdirs(); >>
$ javac -encoding UTF-8 javaapplication/JavaApplication1.java
$ java -Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8 javaapplication.JavaApplication1
If your environment is set to ASCII or not set at all, you will get /tmp/fo?/b?r. If your environment is set to ISO-8859-1 instead, you will get /tmp/fo\366/b\344r. System properties given on the commandline and in the static initialization block have no effect. You have to set your environment to an *.utf-8 locale:
$ LC_ALL=de_DE.utf-8 java javaapplication.JavaApplication1
Now you have a directory tree named /tmp/f\303\266/b\303\244r, which is the correct byte level encoding for UTF-8.
Using java.nio.*
In contrast to java.io, java.nio honors the sun.jnu.encoding system property set in the static initialization block:
package javaapplication1; public class JavaApplication1 < static < System.setProperty("sun.jnu.encoding", "UTF-8"); >public static void main(String[] args) throws java.io.IOException < java.nio.file.Files.createDirectories(java.nio.file.Paths.get("/tmp/foö/bär")); >>
$ javac -encoding UTF-8 javaapplication/JavaApplication1.java
But, you can omit any locale settings and system properties on the command line, and will still get directories with UTF-8 names:
$ java javaapplication.JavaApplication1
package javaapplication1; public class JavaApplication1 < public static void main(String[] args) throws java.io.IOException < java.nio.file.Files.createDirectories(java.nio.file.Paths.get("/tmp/foö/bär")); >>
$ LC_ALL=de_DE.utf-8 java javaapplication.JavaApplication1
Btw, java.nio just defines static functions plus several interfaces. For an object oriented language I find this highly unclean.
Properties File — encoding
This tutorial explains step by step to read and write a properties file in spring boot with encoding default and UTF-8 example with example.
Sometimes, We want to read the properties file that contains non-English characters.
For example, the properties file contains UTF-8 encoding characters. The default encoding for properties file reading is ISO-8859-1 .
Spring framework loads the properties file in default encoding.
In this tutorial, you will learn how to read and write the content of a property file with a specified encoding in Java.
How to configure encoding for Spring boot to read
In this example, you will learn how to Read keys and their values from a property file spring boot application.
Let’s have a properties file — application_fr.properties which contains non-English characters.
There are many ways properties file read in spring core and boot applications.
create a Bean object returning PropertiesFactoryBean using the @Bean annotation
set encoding using setFileEncoding method
configure to read properties file from ClassPathResource setLocation method
Next, you can access the properties file mapped to member variables using @Value annotation with the below syntax
Another way, using @PropertySource annotation with value contains the name of file and encoding to `UTF-8
@PropertySource(value = “classpath:/application_properties.properties”, encoding=“UTF-8”)
read individual properties with the getProperty method with encoding
How to read from property file containing utf 8 character in java
Reading properties file is an easy way to do it in java.
You can apply encoding for file input stream as seen in the below example
catch (FileNotFoundException fie) < fie.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >System.out.println(properties.getProperty("hostname")); Set keys = properties.stringPropertyNames(); for (String key : keys) < System.out.println(key + " - " + properties.getProperty(key)); >> >
Conclusion
You learned how to configure properties files to read UTF-8 character encoding in spring framework and boot as well as Java.