读取java中的UTF-8编码数据
时间:2020-02-23 14:35:32 来源:igfitidea点击:
在本教程中,我们将看到如何读取UTF-8编码的数据。
有时,我们必须处理 UTF-8在我们的应用程序中编码数据。
它可能是由于用户输入的处理数据。
有多种方法可以阅读 UTF-8java中的编码数据。
使用文件的newbufferereader()
我们可以用 java.nio.file.Files's newBufferedReader()读取UTF8数据到字符串。
package org.igi.theitroad;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
public class ReadUTF8NewBufferReaderMain {
public static void main(String[] args) {
readUTF8UsingnewBufferReader();
}
//using newBufferedReader method of java.nio.file.Files
public static void readUTF8UsingnewBufferReader() {
Path path = FileSystems.getDefault().getPath("/users/apple/WriteUTF8newBufferWriter.txt");
Charset charset = Charset.forName("UTF-8");
try {
BufferedReader read = Files.newBufferedReader(path, charset);
String line = null;
while ((line = read.readLine()) != null) {
System.out.println(line);
}
read.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用BufferedReader.
我们需要通过编码 UTF8虽然创造新 InputStreamReader。
package org.igi.theitroad;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class ReadUTF8DataMain {
public static void main(String[] args) {
try {
File utf8FilePath = new File("/users/apple/UTFDemo.txt");
BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream(utf8FilePath), "UTF8"));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} catch (Throwable e) {
e.printStackTrace();
}
}
}
使用DataInputStream的Readutf()方法
我们可以用 DataInputStream readUTF()读取UTF8数据到文件。
package org.igi.theitroad;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadUTFDataMain {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("/users/apple/WriteUTFDemo.txt");
DataInputStream dis = new DataInputStream(fis);
String utf8FileData = dis.readUTF();
System.out.println(utf8FileData);
dis.close();
} catch (EOFException ex) {
System.out.println(ex.toString());
} catch (IOException ex) {
System.out.println(ex.toString());
}
}
}

