1.通过string.getBytes(charsetNane)获得的字节数组,字节数组的编码方式,决定了FileOutStream写出文件的格式

例1:字节数组采用“GBK”编码,write生成的文件也将是“GBK”编码

package cn.edu.uestc.IO;

import java.io.*;

public class TestFileOutputStream01 {
public static void main(String[] args){
//源
File src = new File("abc5.txt");//如果没有文件,自动创建
//流
OutputStream os = null;
try {
os = new FileOutputStream(src,false);
//操作
String str = "你好,哈哈哈";
byte[] bytes = str.getBytes("GBK");//字节数组采用GBK编码
os.write(bytes,0,bytes.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//释放资源
try{
if (os!=null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

文件类型:

纯文本-FileOutputStream的解码方式-LMLPHP

例2:字节数组采用“UTF-8”编码,write生成的文件也将是“UTF-8”编码

package cn.edu.uestc.IO;

import java.io.*;

public class TestFileOutputStream02 {
public static void main(String[] args){
//创建源
File src = new File("abc6.txt");
//生成流
OutputStream os = null;
try {
os = new FileOutputStream(src);
//操作
String str = "你好,哈哈哈";
byte[] bytes = str.getBytes("UTF-8");//字节数组采用"UTF-8"编码
os.write(bytes,0,bytes.length);
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if (null!=os){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

文件类型:

纯文本-FileOutputStream的解码方式-LMLPHP

05-12 04:30