FileOutputStream向文件输出中文
因为write方法中参数没有String,所以向文件中输出中,得把字符串转换成byte[]数组。
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputStreamTest01 {
public static void main(String[] args) {
FileOutputStream fos=null;
try {
fos=new FileOutputStream("test",true);
byte[] b= {97,98,99,100};
fos.write(97);
fos.write(b);
//输出流向文件中输出中文的方式
fos.write("我喜欢你".getBytes());
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
FileInputStream读取中文文件
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileInputStringTest01 {
public static void main(String[] args) {
FileInputStream fis=null;
try {
fis=new FileInputStream("C:\\test\\copy.txt");
byte[] b=new byte[50];
int readcount;
while(( readcount=fis.read(b))!=-1){
System.out.print(new String(b,0,readcount));}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
字符流读取中文
在网上查了资料,发现idea的控制台用的是GBK编码。
import java.io.*;
public class FileInputStringTest01 {
public static void main(String[] args) {
//FileReader reader=null;
FileInputStream fi=null;
InputStreamReader reader=null;
try {
fi=new FileInputStream("C:\\test\\copy.txt");
reader=new InputStreamReader(fi,"GBK");
// reader=new FileReader("C:\\test\\copy.txt","UTF-8");
char[] c=new char[10];
int readcount;
while(( readcount=reader.read(c))!=-1){
System.out.print(new String(c,0,readcount));}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}