在Java IO流中,基于字节操作的I/O接口有InputStream和OutputStream;基于字符操作的I/O接口有:Writer和Reader;字符与字节的转化桥梁是InputStreamReader和OutputStreamWriter.
以读取文件为例,
File file = new File("文件路径,如H:/object.txt");
将字符串以某种编码格式写入代码如下:
try {
//方法一:可自选编码格式,在文件末尾写入数据
//字节流关联文件file
FileOutputStream fos = new FileOutputStream(file,true);
//字符流转化为字节流,编码
OutputStreamWriter osw = new OutputStreamWriter(fos,"编码格式");
//字符流读入数据
BufferedWriter bw = new BufferedWriter(osw);
bw.write(str);
bw.close();
/* //方法二:无法选择编码格式,覆盖原内容文件
//FileWriter 继承 OutputStreamWriter,只有构造器,没有方法
FileWriter fw = new FileWriter(file);
fw.write(str);
fw.close();*/
} catch (IOException e) {
e.printStackTrace();
}
读取文件代码如下:
try {
//字节读取文件file的磁盘数据
FileInputStream fis = new FileInputStream(file);
//字节转化为字符,用于print()
InputStreamReader isr = new InputStreamReader(fis,"编码格式");
//字符char读取
BufferedReader br = new BufferedReader(isr);
int num;
char ch;
while( (num = br.read()) != -1){
ch = (char) num;
System.out.print(ch);
System.out.print(",");
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
若文件后缀为.txt,会发现输出与输入不完全一样,是因为txt文件后自动添加文件头.
编码格式 | 文件头的十六进制数据 |
ANSI | 无文件头 |
UTF-8 | EF BB BF |
Unicode | FF FE |
Unicode-big | FE FF |
如何查看txt的文件头数据,请参考http://blog.csdn.net/skdhyrs/article/details/78240861