在Java中写入UTF-8编码数据
时间:2020-02-23 14:35:39 来源:igfitidea点击:
在本教程中,我们将看到如何编写UTF-8编码的数据。
有时,我们必须处理 UTF-8在我们的应用程序中编码数据。
它可能是由于用户输入的处理数据。
我们将使用印地语语言句子来写入文件。
有三种方式来写 UTF-8java中的编码数据。
使用文件的newbufferwriter()
我们可以用 java.nio.file.Files's newBufferedWriter()将UTF8数据写入文件。
package org.igi.theitroad;
import java.io.BufferedWriter;
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 WriteUTF8NewBufferWriter {
public static void main(String[] args) {
writeUTF8UsingnewBufferWriter();
}
//using newBufferedWriter method of java.nio.file.Files
private static void writeUTF8UsingnewBufferWriter() {
Path path = FileSystems.getDefault().getPath("/users/apple/WriteUTF8newBufferWriter.txt");
Charset charset = Charset.forName("UTF-8");
try {
BufferedWriter writer = Files.newBufferedWriter(path, charset);
writer.write("यह फ़ाइल UTF-8 newBufferWriter से लिखी गई है");
writer.flush();
writer.close();
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
}
}
当我们运行上述程序时, WriteUTF8newBufferWriter.txt将在 /users/apple/WriteUTF8newBufferWriter.txt。
让我们打开文件并看看内容。
使用bufferedwriter.
我们需要通过编码 UTF8虽然创造新 OutputStreamWriter。
package org.igi.theitroad;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
public class WriteUTF8DataMain {
public static void main(String[] args) {
try {
File utf8FilePath = new File("/users/apple/UTFDemo.txt");
Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(utf8FilePath), "UTF8"));
writer.append("UTF-8 Demo for theitroad.com").append("\r\n");
writer.append("यह हिंदी का वाक्य है").append("\r\n");
writer.flush();
writer.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
catch (Throwable e) {
e.printStackTrace();
}
}
}
当我们运行上述程序时, UTFDemo.txt将在 /users/apple/UTFDemo.txt。
让我们打开文件并看看内容。
使用DataOutputStream的WriteUtf()方法
我们可以用 DataOutputStream's writeUTF()将UTF8数据写入文件。
package org.igi.theitroad;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteUTFMain {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("/users/apple/WriteUTFDemo.txt");
DataOutputStream dos = new DataOutputStream(fos);
dos.writeUTF("आप कैसे हैं");
dos.close();
}
catch(EOFException ex) {
System.out.println(ex.toString());
}
catch(IOException ex) {
System.out.println(ex.toString());
}
}
}

